I would like to capture an image from the camera and save it to the private app cache directory. I realize that I have to give the camera app permission to write to my private directory, so I added the FLAG_GRANT_WRITE_URI_PERMISSION flag.
What's happening is, that the camera app opens, I can take the picture, but when i click on the OK button, nothing happens. The camera app stays open. No log output. I guess it's because of a permission problem.
private void getCameraImage() {
try {
mTmpFile = File.createTempFile("tmp", ".jpg", getCacheDir());
Uri imgUri = Uri.fromFile(mTmpFile);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// i.setData(imgUri); // if uncommented, i get an ActivityNotFound Exception
startActivityForResult(i, REQUEST_CAMERA);
} catch (IOException e) {
Log.e(TAG, "getCameraImage()", e);
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
Any insights, on how I could correct that?
Edit:
When I change the directory to the public SD card, then it works fine.
mTmpFile = File.createTempFile("tmp", ".jpg", Environment.getExternalStorageDirectory());
Thanks
Simon
Instead of passing the Uri to store the picture you can use http://developer.android.com/reference/android/hardware/Camera.html#takePicture(android.hardware.Camera.ShutterCallback, android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback)
and get the content in your app memory. From there you will be able to do anything you want.
Do not forget that camera applications are using also the gallery and the gallery app is not allowed to check your private directory.
Related
I am saving image bytes through my application using this simple method:
public static boolean StoreBytesToFile(byte[] messagebytes, String FilePathName)
{
try
{
FileOutputStream fos = new FileOutputStream(FilePathName);
fos.write(messagebytes);
fos.flush();
fos.close();
}
catch(java.io.FileNotFoundException fnfe)
{
return false;
}
catch(java.io.IOException ioe)
{
return false;
}
return true;
}
And then when user wants to see the stored image, I open it using gallery intent:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + m_ImageFilename);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
However, gallery shows only the single image file pointed by m_ImageFilename despite there are other images stored in the same folder.
Thus actual behaviour of gallery intent is this:
While expected behaviour is this:
As an important note, I must mention that after restarting phone, gallery intent shows all images in folder as expected. Also, the behaviour is same on all versions from Jelly Bean to Marshmallow.
So each time after saving image, user has to restart phone in order to see all images in folder through gallery intent.
Please can someone tell what am I missing here and how can this be fixed?
You need to add saved image to gallery ... This will help you.
I am trying to take photo using IMAGE_CAPTURE intent and show this photo on the screen immediately. What I do:
File photoFile = createImageFile();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, REQUEST_CAMERA);
Create image file method:
private File createImageFile() {
File dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File photoFile = null;
try {
photoFile = File.createTempFile("photo", ".jpg", dir);
mPhotoPath = photoFile.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return photoFile;
}
When onActivityResult is called I execute:
Bitmap photo = BitmapFactory.decodeFile(mPhotoPath);
mPhoto.setImageBitmap(photo);
Here is a problem. Apparently IMAGE_CAPTURE activity saves image to a file in background and my onActivityResult gets executed before image is saved. Because of this my photo == null. Although it works if I put breakpoint before BitmapFactory.decodeFile call. I fixed it with an ugly hack:
while (photo == null) {
photo = BitmapFactory.decodeFile(mPhotoPath);
}
So, am I doing something wrong? Why it works this way?
I am testing on Marshmallow Nexus 5.
Apparently IMAGE_CAPTURE activity saves image to a file in background and my onActivityResult gets executed before image is saved
I would consider that to be a bug in the specific camera app that is handling your request. There are hundreds, if not thousands, of such camera apps, and bugs like this are somewhat common.
I fixed it with an ugly hack
Busy loops like that are never a good idea. Among other things, it will freeze your UI if done in the main application thread, and it will seriously chew up CPU even if done on a background thread.
I would try a FileObserver to watch for when the file is closed, to be more event-driven. If, for whatever reason, you can't get that to work:
make sure you are doing your watch-for-the-file logic in a background thread
add reasonable SystemClock.sleep() periods between tries (e.g., 50ms)
Regardless of whether I use an emulated camera or use my webcam as the emulated device's camera, I cannot save photos. My code sets up a new file to save the photo, the camera activity pops up, but after I take the picture, hitting the 'save' or 'accept picture' button doesn't do anything. The only way I can return to my app's activity it by hitting cancel. This code works when I run it on my Galaxy S3, but not an emulated Nexus device. When I set up the device in AVD Manager, I always make sure to enable to set both cameras to either emulated or webcam0, whichever I am using, and I make sure to have an SD card (even though I save to internal memory) and internal storage sufficient for photos. In my manifest, I declare android.permission.INTERNET, android.permission.WRITE_EXTERNAL_STORAGE, and android.permission.CAMERA. Any ideas?
Here's my code where I start the camera intent:
private void dispatchTakePictureIntent(int position) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile(position);
} catch (IOException ex) {
Log.v("photo", "photoFile failed.");
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
} else {
Log.v("tag", "photoFile was equal to null.");
}
}
}
Found a solution! The emulated camera wasn't returning because I used a bad directory (selected in createImageFile above) for saving the File. I started using the directory returned by Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) and that solved the problem.
I'm currently trying to save images taken from a phone to its gallery, but the code below only works if I choose the stock camera app when the chooser dialog pops up. Whenever I choose another camera app(e.g., the Google camera), the taken picture doesn't get saved any where.
To make things even stranger, sometimes the picture does show up in its designated directory in the gallery, but after 15 mins or so, the same goes for when I use the stock camera app: the picture will get saved in the default camera shots directory, but takes quite a bit to show up in its designated directory, if it shows up there at all.
// Capturing Camera Image will launch camera app request image capture
void captureImage() {
//file uri to store image.
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// Request camera app to capture image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
getActivity().startActivityForResult(captureIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
well ,
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
does not work anymore .
you should do something like this :
call Camera Activity :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
and onActivityResult :
if (data.getData() == null) {
Bitmap bm = (Bitmap)
data.getExtras().get("data");
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss").format(new Date());
File pictureFile = new File(Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp);
try {
FileOutputStream fos = new FileOutputStream(
pictureFile);
bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
String filePath = pictureFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} } else {
Uri imgUri =data.getData());
}
It turns out my code was working after all. The pictures were being saved in the new directory, but the problem was that the gallery wasn't being updated, which explains why the photos would randomly appear in the directory later on. Being new to this, it never occurred to me that I would have to update the gallery. I only came to this realization after using ES File Explorer to look through my files. To fix my problem, I just made a new method in my CameraFragment that would call on the media scanner. I called this method from onActivityResult().
Here's the new method, though there's nothing really "new" about it since I ran into the same code on other SO questions:
protected void mediaScan() {
getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse(fileUri.toString())));
}
I also don't need to call the package manager and iterate through the apps that could handle the camera intent if I'm not giving the option to use choose a picture from a gallery, so I'm going to remove all that from my question.
I am trying to invoke the default device camera from my application to take picture using intent android.provider.MediaStore.ACTION_IMAGE_CAPTURE. Everything seems to be working fine except for when i click and save a particular image it gets stored at two location
1. At the default camera location.
2. At the location which i am passing with intent.
I just want the 2nd option to happen and not the 1st one. I thought creating a .nomedia file in used defined location would make sure that the picture would not be listed as part of gallery but later i found that the pic is getting stored at both the location.
My relevant portion of code is:
In the Activity:
Intent intentCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
tempDir = Environment.getExternalStorageDirectory();
// place where to store camera taken picture
photo = createTemporaryFile("picture", ".jpg", tempDir);
photo.delete();
} catch (Exception e) {
Toast.makeText(this, "Please check SD card! Error in fetching image",
Toast.LENGTH_SHORT).show();
}
if (photo != null) {
Uri mImageUri = Uri.fromFile(photo);
Log.i(TAG, "" + mImageUri.toString());
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
}
startActivityForResult(intentCamera, CAMERA_PIC_REQUEST);
The corresponding method.
public File createTemporaryFile(String part, String ext,File tempDir) throws Exception {
tempDir = new File(tempDir.getAbsolutePath() +"/temp/");
if (!tempDir.exists()) {
tempDir.mkdir();
}
createNoMediaFile(tempDir.getAbsolutePath());
return File.createTempFile(part, ext, tempDir);
}
Is there a way i can avoid 1 i.e. saving the image to the default gallery location. Thanks.
onActivityResult returns you the Uri of Image you can retrieve the path of Image copy the image from that location and save at your desired location and after that delete that from Gallery.