am trying to create a folder on sdcard and save all images there and not on internal memory.
public class CameraActivity extends Activity {
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView mImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImage = (ImageView) findViewById(R.id.result);
//1
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File image = new File(Environment.getExternalStorageDirectory()+File.separator +"mypics");
Uri fileUri = Uri.fromFile(image);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
EditText etext = (EditText) findViewById(R.id.editTextLocation);
Toast.makeText(getBaseContext(), data.getExtras().get("data").toString(), Toast.LENGTH_LONG).show();
mImage.setImageBitmap(thumbnail);
etext.setText(data.getExtras().get("data").toString());
//3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
String state=Environment.getExternalStorageState();
Toast.makeText(getBaseContext(), state, Toast.LENGTH_LONG).show();
File file = new File(Environment.getExternalStorageDirectory()+File.separator +"mypics");
if(!file.exists())
if(file.mkdirs())
Log.v("Mobitracker","success");
if (Environment.MEDIA_MOUNTED.equals(state))
Toast.makeText(getBaseContext(), "Yes its read only", Toast.LENGTH_LONG).show();
if ( Environment.isExternalStorageRemovable ())
Toast.makeText(getBaseContext(), "Yes its internal card", Toast.LENGTH_LONG).show();
//Create New file and name it Image2.PNG
File file1 = new File(file, "Image2.PNG");
try {
file1.createNewFile();
FileOutputStream fo = new FileOutputStream(file1);
//5
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
Toast.makeText(getBaseContext(), "Please take snap again", Toast.LENGTH_LONG).show();
}
}
This is my code for it, I tried many things but stillnot possible it is saving in internalmemory DCIM folder why?
Am getting output as
Mounted
Yes its read only
Am not connected to system but still same problem I even tried restarting phone and all but still same.
Am using sony xperia tipo mobile 4.0.4 os.
Please help me its frustrating I tried all threads.
can you guys help me please
My permissions are
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
And also I could see bitmap image in image view but
Toast.makeText(getBaseContext(), data.getExtras().get("data").toString(),Toast.LENGTH_LONG).show();
is returning some android.graphics#422020 some thing
You should use outputstream to write the content. Refer here for help.
Or do something like (see here the complete thread):
Button.OnClickListener buttonSaveOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
OutputStream outStream = null;
File file = new File(extStorageDirectory, "er.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(AndroidWebImage.this, "Saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(AndroidWebImage.this, e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(AndroidWebImage.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
};
Read this Android Training post carefully to figure things out. As the post says,
The Android Camera application saves a full-size photo if you give it a file to save into.
so if you did pass the Uri of a file,it will be stored in DCIM only and you should access the image using this Uri.
Check out similar thread
Related
I need to save some files into my Android phone.
So I used something like:
FileOutputStream os = null;
try{
os = new FileOutputStream("/root/sdcard/DCIM/1.jpg");
os.write(bytes);
os.close();
}catch(FileNotFoundException e){}
When I do this, it would say something like
java.io.FileNotFoundException: /root/sdcard/DCIM/1.jpg (Permission denied)
Btw, I already requestd permission in AndroidManifest.xml using something like:
<user-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I also tried
getFilesDir().getAbsolutePath();
And it actually refers to
/data/user/0/come.package.xxx/files
Which I have no idea where this path is because I could not find it on my phone.
When I use ASUS File Manager, I see the path is /root/sdcard/..., but I don't even have a sdcard in my phone, I have been using iPhone for many years now, so I don't know how the Android file system works now.
This is really confusing for me, could someone explain it to me how the Android file system works? Thank you all!
if you are using android 6.0 Marsh or higher android version u need to give run time permission to access.try below code
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
camera.setEnabled(false);
ActivityCompat.requestPermissions(getActivity(), new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//permission will get success here
//do what you want
}
else {
//Permission not granted
Toast.makeText(getActivity(),"You need to grant camera permission to use camera",Toast.LENGTH_LONG).show();
}
}
}
To save image on Android:
private String saveToInternalStorage(String name, Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir(IMAGE_TAG, Context.MODE_PRIVATE);
// Create imageDir
File mypath = new File(directory, name + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
To load image:
public void loadImage(ImageView imageView) {
// get path
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir(IMAGE_TAG, Context.MODE_PRIVATE);
String path = directory.getAbsolutePath();
// load image
try {
File f = new File(path, name + ".jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
imageView.setImageBitmap(b);
imageView.setVisibility(View.VISIBLE);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Image", "Image file not found.");
}
}
if your are using marshmallow or latest version of android so you need to provide permission at run time, on your buttom click than you need to call your code for saving file into sd card.
after than do like this,
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
I am trying to save and retrieve a Bitmap from internal storage but everytime I try to load bitmap, BitMapFactory throws Exception:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: android.graphics.Bitmap#b35e414: open failed: ENOENT (No such file or directory)
I have tried nearly all solutions given by similar threads on this website, but none worked for me.
And this exception is thrown 4 times, though I am reading only one image.How?
And this is the code I am using to save and retrieve images from storage.
public static void saveFile(Context context, Bitmap b, String picName) {
FileOutputStream fos;
try {
fos = context.openFileOutput(picName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (IOException e) {
Log.e("store DRV image", e.getMessage());
e.printStackTrace();
}
}
public static Bitmap loadBitmap(Context context, String picName) {
Bitmap b = null;
FileInputStream fis;
try {
fis = context.openFileInput(picName);
b = BitmapFactory.decodeStream(fis);
fis.close();
} catch (IOException e) {
Log.e("get stored DRV image", e.getMessage());
e.printStackTrace();
}
return b;
}
I got this code from a thread on this website, and all comments were good. But its not working for me. I have added permissions in Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Lastly, I am using random generated UIDs as filename. The UIDs are generated using Firebase SDK. So the UID may contain numbers or other characters like
XXgKbRiS5ogQz1euqiyRsC1ggBS2. So is this a wrong way to name a file? and hence exception is thrown?
Add this code in onCreate() of your Activity:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
catch the result in same activity using:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 0: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
//call your method
} else {
Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Learn more about Runtime Permission from HERE
You need to add user permission above 6.0:
Add library:
compile 'pub.devrel:easypermissions:0.2.1'
private String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(this, galleryPermissions)) {
pickImageFromGallery();
} else {
EasyPermissions.requestPermissions(this, "Access for storage",
101, galleryPermissions);
}
//Make sure permission are granted
//For saving
File file=saveFile(contex,bitmap,picName);
//For fetching
File dir = new File(Environment.getExternalStorageDirectory(), picName);
BitmapFactory.decodeFile(file.getPath())
/**
* #param context
* #param b
* #param picName
*/
public static File saveFile(Context context, Bitmap b, String picName) {
FileOutputStream fos;
File dir = new File(Environment.getExternalStorageDirectory(), "My Images");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, picName);
try {
fos = context.openFileOutput(file.getPath(), Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (IOException e) {
Log.e("store DRV image", e.getMessage());
e.printStackTrace();
}
return file;
}
I am following this answer to accomplish my task. Everything works well except the last part,
if(result!=null)
{
Toast.makeText(getApplicationContext(), "Image saved in Gallery !", Toast.LENGTH_LONG).show();
if(isinint) //check if any app cares for the result
{
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND, Uri.fromFile(new File(result.toString()))); //Create a new intent. First parameter means that you want to send the file. The second parameter is the URI pointing to a file on the sd card. (openprev has the datatype File)
((Activity) ImageListActivity.this).setResult(Activity.RESULT_OK, shareIntent); //set the file/intent as result
((Activity) ImageListActivity.this).finish(); //close your application and get back to the requesting application like GMail and WhatsApp
return; //do not execute code below, not important
}
}
At last nothing crash but wallpaper is also not set in whatsapp.
Can anyone please let me know why it is not working?
Any help is appriciated.
Thanks
You can use the following code..
OnButtonClick(){
ImageProcessing imageProcessing = new ImageProcessing();
Bitmap bitmap = imageProcessing.takeScreenshot(getWindow().getDecorView().findViewById(R.id.view_thought));
imageProcessing.saveBitmap(bitmap);
Intent intent = imageProcessing.setAsOption(this,imageProcessing.getSavedImagePath());
startActivityForResult(Intent.createChooser(intent, "Set image as"), 200);
}
And Implement a new class ImageProcessing
public class ImageProcessing {
private File imagesPath;
public void saveBitmap(Bitmap bitmap) {
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagesPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("POS", e.getMessage(), e);
} catch (IOException e) {
Log.e("POS", e.getMessage(), e);
}
}
public File getSavedImagePath(){
imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");
return imagesPath;
}
public Bitmap takeScreenshot(View rootView) {
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public Intent setAsOption(Context cntxt,File imagesPath){
/*File imagesPath = new File(Environment.getExternalStorageDirectory() + "/screenshot.jpg");*/
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
if(imagesPath.exists()){
Uri contentUri = FileProvider.getUriForFile(cntxt, BuildConfig.APPLICATION_ID+".Utility.GenericFileProvider",imagesPath);
intent.setDataAndType(contentUri, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
Toast.makeText(cntxt,"Not a wallpaper",Toast.LENGTH_SHORT).show();
}
return intent;
}
}
And in menifest add :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using Camera and storing captured result in SDCard in android
I want to get picture from camera app, save it on SD and set imageView.
I made a code below. saving and imageView sometimes works. but sometimes the picture is saved on SD and imageView doesn't work.
When imageView doesn't work, it seems that mOutUri become null in onActivityResult.
I have tried to save a mOutUri on SharedPreferences in clkbutton. I can see the uri in onActivityResult but imageView doesn't work. at this time, mOutUri is also null.
public void clkbutton(View v){
Intent intent = new Intent();
// open camera app
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// save data in SD card
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String newPicFile = df.format(date) + ".jpg";
mNewPicFile = newPicFile;
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mOutUri = Uri.fromFile(outFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutUri);
startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageURI(mOutUri);
}
It's so weird that it sometimes errors and sometimes works.
In onActivityResult before you setImageUri you should check if file exists. You can lose mOutUri content when app changes orientation, and it happend sometime when you open camera. You should implement in activity onSaveInstanceState where you store into preferences your uri and onRestoreInstanceState where you restore your uri.
try the following code:
static Uri capturedImageUri=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(), (cal.getTimeInMillis()+".jpg"));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
capturedImageUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(i, CAMERA_RESULT);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
//Bitmap photo = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(photo);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap( getApplicationContext().getContentResolver(), capturedImageUri);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and also dont forget to add some permissions in android manifets file like:
`note: add permission WRITE_EXTERNAL_STORAGE in manifest file.`
I am having a problem capturing an image and storing it from the native camera app. Here is a sample of some of my code.
_path = Environment.getExternalStorageDirectory() + "make_machine_example.jpg";
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, 0 );
After the picture has been taken and I'm returned back to my original Activity, When I navigate to my sd card via Android DDMS File Explorer the picture is not there. Anyone know why this is not being saved?
Here was the final product in case anyone is still visiting this thread:
public class CameraCapture extends Activity {
protected boolean _taken = true;
File sdImageMainDirectory;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName");
startCameraActivity();
}
} catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
protected void startCameraActivity() {
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
} catch (Exception e) {
e.printStackTrace();
}
finish();
startActivity(new Intent(CameraCapture.this, Home.class));
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Have you checked what the output of Environment.getExternalStorageDirectory() is, because if it does not contain a trailing file seperator (/) then your image will end up in a directory that does not reside on the SDcard such as:
/mnt/sdcardmake_machine_example.jpg
When what you really want is:
/mnt/sdcard/make_machine_example.jpg
Try this code instead:
_path = Environment.getExternalStorageDirectory() + File.separator + "make_machine_example.jpg";
1 . Just use
new File(Environment.getExternalStorageDirectory(), "make_machine_example.jpg");
and don't bother about separators.
2 . Faced the same problem before. SenseUI phones have a custom camera application that doesn't create file. What device are you using? It may already be fixed in latest devices but it may also still be an issue. So here's a complete sample how to overcome it Problems saving a photo to a file.
You should perform a media scanning after saving the image
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Add this line into AndroidManifest.xml file and remove extension make_machine_example:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It will start to capture the Photo and store into the SDcard.