173

We are trying to use the native camera app to let the user take a new picture. It works just fine if we leave out the EXTRA_OUTPUT extra and returns the small Bitmap image. However, if we putExtra(EXTRA_OUTPUT,...) on the intent before starting it, everything works until you try to hit the "Ok" button in the camera app. The "Ok" button just does nothing. The camera app stays open and nothing locks up. We can cancel out of it, but the file never gets written. What exactly do we have to do to get ACTION_IMAGE_CAPTURE to write the picture taken to a file?

Edit: This is done via the MediaStore.ACTION_IMAGE_CAPTURE intent, just to be clear

14 Answers 14

147

this is a well documented bug in some versions of android. that is, on google experience builds of android, image capture doesn't work as documented. what i've generally used is something like this in a utilities class.

public boolean hasImageCaptureBug() {

    // list of known devices that have the bug
    ArrayList<String> devices = new ArrayList<String>();
    devices.add("android-devphone1/dream_devphone/dream");
    devices.add("generic/sdk/generic");
    devices.add("vodafone/vfpioneer/sapphire");
    devices.add("tmobile/kila/dream");
    devices.add("verizon/voles/sholes");
    devices.add("google_ion/google_ion/sapphire");

    return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
            + android.os.Build.DEVICE);

}

then when i launch image capture, i create an intent that checks for the bug.

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (hasImageCaptureBug()) {
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/tmp")));
} else {
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
startActivityForResult(i, mRequestCode);

then in activity that i return to, i do different things based on the device.

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
     switch (requestCode) {
         case GlobalConstants.IMAGE_CAPTURE:
             Uri u;
             if (hasImageCaptureBug()) {
                 File fi = new File("/sdcard/tmp");
                 try {
                     u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), fi.getAbsolutePath(), null, null));
                     if (!fi.delete()) {
                         Log.i("logMarker", "Failed to delete " + fi);
                     }
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
             } else {
                u = intent.getData();
            }
    }

this saves you having to write a new camera app, but this code isn't great either. the big problems are

  1. you never get full sized images from the devices with the bug. you get pictures that are 512px wide that are inserted into the image content provider. on devices without the bug, everything works as document, you get a big normal picture.

  2. you have to maintain the list. as written, it is possible for devices to be flashed with a version of android (say cyanogenmod's builds) that has the bug fixed. if that happens, your code will crash. the fix is to use the entire device fingerprint.

11
  • 21
    on Galaxy S: intent.getData() returns null, and moreover, camera app on Galaxy s inserts new photo into gallery by itself, but no uri returned. So if you insert photo from file into gallery, there will be duplicated photo.
    – Arseniy
    Jun 30, 2011 at 9:47
  • using this code on droid-x and sony xpheria devices. Both devices return intent value as null. also droidx returns resultcode as 0 whereas xpheria returns resultcode as -1. Anyone know why that should be the case.
    – rOrlig
    Sep 28, 2011 at 20:14
  • 5
    The link to the "well documented bug" which is at the beginning of yanokwa's answer is incorrect. That bug is about calling the camera app without putExtra(EXTRA_OUTPUT,...) Apr 10, 2012 at 14:42
  • code.google.com/p/android/issues/detail?id=1480 Well, how do you explain this then? May 10, 2013 at 10:00
  • Has this bug been fixed yet? Jun 5, 2013 at 17:02
52

I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.

I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:

String storageState = Environment.getExternalStorageState();
        if(storageState.equals(Environment.MEDIA_MOUNTED)) {

            String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
            _photoFile = new File(path);
            try {
                if(_photoFile.exists() == false) {
                    _photoFile.getParentFile().mkdirs();
                    _photoFile.createNewFile();
                }

            } catch (IOException e) {
                Log.e(TAG, "Could not create file.", e);
            }
            Log.i(TAG, path);

            _fileUri = Uri.fromFile(_photoFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
            intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
            startActivityForResult(intent, TAKE_PICTURE);
        }   else {
            new AlertDialog.Builder(MainActivity.this)
            .setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
            .setCancelable(true).create().show();
        }

I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.

Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg

There is no need to copy the file in the "onActivityResult" as posted above.

3
  • 13
    Make sure you have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in your manifest if you are using newer than Android 1.5 -- spent a few hours debugging the camera stuff and this wasn't included so my saves would always fail.
    – swanson
    Sep 8, 2011 at 21:00
  • This works good for me, but every about 10 images or so, the blank file is not overwritten and I end up with a 0 byte file where the image should be. It's very annoying and has been tough to track down.
    – joey_g216
    Oct 7, 2011 at 2:12
  • 2
    on some devices, such as the nexus 7 with jelly bean, you need to change Environment.getExternalStorageDirectory().getName() to use .getAbsolutePath() instead of .getName()
    – Keith
    Jul 18, 2012 at 20:28
37

I've been through a number of photo capture strategies, and there always seems to be a case, a platform or certain devices, where some or all of the above strategies will fail in unexpected ways. I was able to find a strategy that uses the URI generation code below which seems to work in most if not all cases.

mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
            new ContentValues());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE_CONTENT_RESOLVER);

To contribute further to the discussion and help out newcomers I've created a sample/test app that shows several different strategies for photo capture implementation. Contributions of other implementations are definitely encouraged to add to the discussion.

https://github.com/deepwinter/AndroidCameraTester

6
  • This was great. I've yet to test this across all my devices, but I'm assuming you have done so quite a bit already. There's so much noise on this topic, and this particular answer is so simple and clean. Works on Nexus 5 so far, which is where I first got a lot of reports that ACTION_IMAGE_CAPTURE wasn't working without EXTRA_OUTPUT. I do hope this works all across the board, but so far so good. Thx
    – Rich
    Jan 4, 2014 at 2:56
  • 1
    @deepwinter - Thank you sir. I was pulling my hair out but your content resolver solution works well on all the problematic scenarios I had. Feb 4, 2014 at 15:44
  • Kind of late to this party but this has been the only solution to work for me. Thanks a bunch!
    – StackJP
    Oct 21, 2014 at 19:58
  • 1
    can I somehow retrieve the MediaStore.EXTRA_OUTPUT in onActivityResult or do I really have to remember it myself? I would have to persistantly save it so that my app even remembers it if it gets destroyed while a photo is taken...
    – prom85
    Nov 12, 2015 at 7:17
  • It doesn't work on samsung galaxy note 3 with lolipop: ava.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference Aug 16, 2016 at 13:56
31

I had the same problem where the OK button in camera app did nothing, both on emulator and on nexus one.

The problem went away after specifying a safe filename that is without white spaces, without special characters, in MediaStore.EXTRA_OUTPUT Also, if you are specifying a file that resides in a directory that has not yet been created, you have to create it first. Camera app doesn't do mkdir for you.

3
  • 1
    And make sure you use mkdirs() instead of mkdir() if your path has more than one directory level and you want all of them created (mkdir only creates the last one, the 'leaf' directory). I had some problems with that, and this answer helped me.
    – Diana
    Oct 21, 2013 at 14:52
  • can we use simple timestamps ?? or can the also make some errors ?? pleas do tag me when replied :) Nov 29, 2013 at 8:06
  • @user2247689 I am not sure about the file name you created by "simple timestamps" but as long as they don't contain special characters not allowed by FAT format on SD card it should be ok I think.
    – Yenchi
    Dec 2, 2013 at 16:31
28

The workflow you describe should work as you've described it. It might help if you could show us the code around the creation of the Intent. In general, the following pattern should let you do what you're trying.

private void saveFullImage() {
  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
  outputFileUri = Uri.fromFile(file);
  intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
  startActivityForResult(intent, TAKE_PICTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if ((requestCode == TAKE_PICTURE) && (resultCode == Activity.RESULT_OK)) {
    // Check if the result includes a thumbnail Bitmap
    if (data == null) {    
      // TODO Do something with the full image stored
      // in outputFileUri. Perhaps copying it to the app folder
    }
  }
}

Note that it is the Camera Activity that will be creating and saving the file, and it's not actually part of your application, so it won't have write permission to your application folder. To save a file to your app folder, create a temporary file on the SD card and move it to your app folder in the onActivityResult handler.

5
  • This /should/ work, but the camera app's ok button just does nothing. We did get it working writing to the SD card, so I suspect this is a file permissions problem (though I thought that an application automatically had write permissions to it's personal directory). thanks for the help!
    – Drew
    Dec 15, 2009 at 22:34
  • 1
    Your app has write permission to it's personal directory -- the camera app (which is taking the picture) does not. You could move the file in the onActivityResult though, as that's within your app. Alternatively you could implement a camera Activity yourself, but that seems overkill.
    – Reto Meier
    Dec 15, 2009 at 22:36
  • Redoing the camera app seems to be a common but tedious approach... When we use getDir("images",MODE_WORLD_WRITEABLE), does that permission not apply to any file we tell it to create in that directory?
    – Drew
    Dec 15, 2009 at 22:42
  • Not necessarily. The permission is for the folder, not necessarily for the files within it.
    – Reto Meier
    Dec 15, 2009 at 22:54
  • I tested the code with Android devices with Android 2.2 and newer and all of them saved the image to the supplied path. So I guess that this should be standard behaviour to get images.
    – Janusz
    Apr 30, 2013 at 15:04
8

To follow up on Yenchi's comment above, the OK button will also do nothing if the camera app can't write to the directory in question.

That means that you can't create the file in a place that's only writeable by your application (for instance, something under getCacheDir()) Something under getExternalFilesDir() ought to work, however.

It would be nice if the camera app printed an error message to the logs if it could not write to the specified EXTRA_OUTPUT path, but I didn't find one.

4

to have the camera write to sdcard but keep in a new Album on the gallery app I use this :

 File imageDirectory = new File("/sdcard/signifio");
          String path = imageDirectory.toString().toLowerCase();
           String name = imageDirectory.getName().toLowerCase();


            ContentValues values = new ContentValues(); 
            values.put(Media.TITLE, "Image"); 
            values.put(Images.Media.BUCKET_ID, path.hashCode());
            values.put(Images.Media.BUCKET_DISPLAY_NAME,name);

            values.put(Images.Media.MIME_TYPE, "image/jpeg");
            values.put(Media.DESCRIPTION, "Image capture by camera");
           values.put("_data", "/sdcard/signifio/1111.jpg");
         uri = getContentResolver().insert( Media.EXTERNAL_CONTENT_URI , values);
            Intent i = new Intent("android.media.action.IMAGE_CAPTURE"); 

            i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            startActivityForResult(i, 0); 

Please note that you will need to generate a unique filename every time and replace teh 1111.jpg that I wrote. This was tested with nexus one. the uri is declared in the private class , so on activity result I am able to load the image from the uri to imageView for preview if needed.

2
1

I had the same issue and i fixed it with the following:

The problem is that when you specify a file that only your app has access to (e.g. by calling getFileStreamPath("file");)

That is why i just made sure that the given file really exists and that EVERYONE has write access to it.

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File outFile = getFileStreamPath(Config.IMAGE_FILENAME);
outFile.createNewFile();
outFile.setWritable(true, false);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(outFile));
startActivityForResult(intent, 2);

This way, the camera app has write access to the given Uri and the OK button works fine :)

1
  • AndroidRuntime (2.1 emulator) throws NoSuchMethodError: java.io.File.setWritable
    – jwadsack
    May 10, 2011 at 22:39
1

I recommend you to follow the android trainning post for capturing a photo. They show in an example how to take small and big pictures. You can also download the source code from here

0

I created simple library which will manage choosing images from different sources (Gallery, Camera), maybe save it to some location (SD-Card or internal memory) and return the image back so please free to use it and improve it - Android-ImageChooser.

1
  • your link is not working anymore!! why, i saw it 2 weeks ago, and i wanted to use it :( Dec 27, 2012 at 10:01
0

The file needs be writable by the camera, as Praveen pointed out.

In my usage I wanted to store the file in internal storage. I did this with:

Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()!=null)){
    try{
        cacheFile = createTempFile("img",".jpg",getCacheDir());
        cacheFile.setWritavle(true,false);
    }catch(IOException e){}
    if(cacheFile != null){
        i.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(cacheFile));
        startActivityForResult(i,REQUEST_IMAGE_CAPTURE);
    }
}

Here cacheFile is a global file used to refer to the file which is written. Then in the result method the returned intent is null. Then the method for processing the intent looks like:

protected void onActivityResult(int requestCode,int resultCode,Intent data){
    if(requestCode != RESULT_OK){
        return;
    }
    if(requestCode == REQUEST_IMAGE_CAPTURE){
        try{
            File output = getImageFile();
            if(output != null && cacheFile != null){
                copyFile(cacheFile,output);

                //Process image file stored at output

                cacheFile.delete();
                cacheFile=null;
            }
        }catch(IOException e){}
    }
}

Here getImageFile() is a utility method to name and create the file in which the image should be stored, and copyFile() is a method to copy a file.

0

You can use this code

private Intent getCameraIntent() {

    PackageManager packageManager = mContext.getPackageManager();
    List<ApplicationInfo> list = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
    Intent main = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    List<ResolveInfo> launchables = packageManager.queryIntentActivities(main, 0);
    if (launchables.size() == 1)
        return packageManager.getLaunchIntentForPackage(launchables.get(0).activityInfo.packageName);
    else
        for (int n = 0; n < list.size(); n++) {
            if ((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                Log.d("TAG", "Installed Applications  : " + list.get(n).loadLabel(packageManager).toString());
                Log.d("TAG", "package name  : " + list.get(n).packageName);
                String defaultCameraPackage = list.get(n).packageName;


                if (launchables.size() > 1)
                    for (int i = 0; i < launchables.size(); i++) {
                        if (defaultCameraPackage.equals(launchables.get(i).activityInfo.packageName)) {
                            return packageManager.getLaunchIntentForPackage(defaultCameraPackage);
                        }
                    }
            }
        }
    return null;
}
0

It is very simple to solve this problem with Activity Result Code Simple try this method

if (reqCode == RECORD_VIDEO) {
   if(resCode == RESULT_OK) {
       if (uri != null) {
           compress();
       }
    } else if(resCode == RESULT_CANCELED && data!=null){
       Toast.makeText(MainActivity.this,"No Video Recorded",Toast.LENGTH_SHORT).show();
   }
}
1
  • The above incomplete snippet does not merit the simplicity that it claimed. Surely, there are hidden complexities for the unfamiliar traveller. Such as scanning for presence or absence of the file. Such as wither it is publicly available or private to the app. Such as the need for a provider or getting a thumbnail only size. These are information gaps for the unwary traveller needs to be aware of.
    – daparic
    May 16, 2020 at 22:37
0
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED)
    {
        //do not process data, I use return; to resume activity calling camera intent
        enter code here
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.