How to get Uri of image taken with camera and stored to Gallery

11,836

Solution 1

If you start the camera by calling

startActivityForResult(cameraIntent, REQUEST_CODE_CAPTURE_IMAGE_ACTIVITY); // start the camera

in onActivityResult you can capture the mediaURI

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE_CAPTURE_IMAGE_ACTIVITY
                && resultCode == RESULT_OK) {
                Uri imageUri = null;
                if (data != null){
                   imageUri = data.getData();
               }
        }
    }

REQUEST_CODE_CAPTURE_IMAGE_ACTIVITY is a static integer value that's used to identify the request that was made through the intent. This is so if you have multiple startActivityForResults you can identify which one is coming back.

Note that if you pre-insert a URI through EXTRA_OUTPUT you will NOT get the URI back through data.getData(); You will have to store the pre-inserted URI in a variable and retrieve it in your onActivityResult while checking to see if imageUri is null..

Ex.

 Uri imageUri = null;
if (data != null){
   imageUri = data.getData();
}
if (imageUri == null && preinsertedUri != null)
 imageUri = preinsertedUri;

// do stuff with imageUri

Solution 2

Getting a Uri from data.getData() in onActivityResult() was not a solution. This worked on one out of three test devices, and failed also on Motorola Defy emulator.

So here is what I ended up doing:

  1. Call camera with Android.provider.MediaStore.ACTION_IMAGE_CAPTURE, no EXTRA_OUTPUT
  2. Get the Uri of image that is stored in Gallery

This seems to be working nicely with test devices, but I'm still not completely happy with this solution because I'm not totally ensured that the image added lastly is always the image user captured.

Share:
11,836
koskenal
Author by

koskenal

Updated on June 05, 2022

Comments

  • koskenal
    koskenal almost 2 years

    I'm launching camera from my application. I'm using Android.provider.MediaStore.ACTION_IMAGE_CAPTURE with extra android.provider.MediaStore.EXTRA_OUTPUT. If I use EXTRA_OUTPUT or not, photo is added to gallery.

    How to get the Uri of the image in Gallery? I haven't found a clean way to do this, and I don't want to use the Uri of last added image to Gallery, because I can not be sure that it is the photo user took.

    Edit: Let me add here, that I do know how to get the image. Currently I'm using my Uri which I'm passing with Intent as an EXTRA_OUTPUT. That is not the problem. The problem is that using this method I get two photos written to sdcard, and I prefer that only one is written. Or in case of two is written, one in gallery and one in my own Uri, I would like to use one of those Uri:s and delete the other one. In both of the cases, I need the Uri of the photo, which is saved to Gallery by default.