How to launch android camera using intents


Instead of writing your own activity to capture the pictures you probably prefer (in most cases)  to use existent Camera activity which actually have good UI and features. It’s really easy to do, just launch it with Intent like in the code below.

You should be notified that using that approach doesn’t work well on API before 2.0 (at least on G1 with 1.6 it save with pictures with 512*384 resolution). On phones with API 2.0+ it save full-sized picture.  So you could use the “How to use autofocus in Android” as the starting point to create your own Camera application.

//define the file-name to save photo taken by Camera activity
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
		MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

the code above should start the default Camera activity on your phone, now lets define the code to handle results returned by this Intent. Please take a notice that “imageUri” is the activity attribute, define and save it for later usage (also in onSaveInstanceState)

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
    if (resultCode == RESULT_OK) {
        //use imageUri here to access the image

    } else if (resultCode == RESULT_CANCELED) {
        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
    } else {
        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
    }
}
}

to get the reference to File object from imageUri you can use the following code.

public static File convertImageUriToFile (Uri imageUri, Activity activity)  {
Cursor cursor = null;
try {
    String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
    cursor = activity.managedQuery( imageUri,
            proj, // Which columns to return
            null,       // WHERE clause; which rows to return (all rows)
            null,       // WHERE clause selection arguments (none)
            null); // Order-by clause (ascending by name)
    int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
    if (cursor.moveToFirst()) {
        String orientation =  cursor.getString(orientation_ColumnIndex);
        return new File(cursor.getString(file_ColumnIndex));
    }
    return null;
} finally {
    if (cursor != null) {
        cursor.close();
    }
}
}

As you see you may get some more information about the image, like orientation, etc, but for things like Thumbnail – you will get null results in most cases, since the thumbnail is not yet created and you should either open Gallery to create the thumbnail or initiate it by calling MediaStore.Images.Thumbnails.getThumbnail (this is the blocking method and was introduced in API-5)

About these ads

https://www.facebook.com/achorniy

Tagged with: , , ,
Posted in Android, Tips and Tricks
55 comments on “How to launch android camera using intents
  1. Lars says:

    Hello!
    I can’t get convertImageUriToFile to work. Can I call it after :

    if (resultCode == RESULT_OK) {
    //use imageUri here to access the image

    If so, which activity should I send to the method???

    Thanks, Lars

  2. Lars says:

    Hmmm, I passed along “this”, works great…
    Thanks, for a nice example.

  3. Vp says:

    I get file named differently from the convertImageUriToFile than I have been defined before calling camera intent. I want image name to be “MyImageName.jpg” but I get 123124235436.jpg.

  4. grennis says:

    The image returned in the imageUri has lost the orientation which I believe is stored in the EXIF. Also the image seems to have been re-saved (re-compressed) and is much smaller file size and I assume lost a lot of quality. These are probably both the same problem; the image is being re-saved. Why?

    I assume you had the orientation problem as well since you appear to retrieve the orientation in the query but you didn’t do anything with it.

    Any ideas?

    • Andrey Chorniy says:

      What device/API-version are you using ?
      I experience that with Android G1 (1.6), and G1 actually save images without EXIF meta-information, Motorola Droid (2.1, 2.2) – always return landscape image with EXIF.
      If you are using 1.6 (G1) – you have no way to obtain good image by calling an intent, the workaround is to create your own Camera-Activity in which you are saving the image, you can find an example here.
      http://achorniy.wordpress.com/2009/12/29/how-to-use-autofocus-in-android/

  5. CipLu says:

    how to save the image form zxing captured via Intent???

    • Andrey Chorniy says:

      Are you asking me about that or want to post it to ZXing forum ? Or you think I’m the author of ZXing ?
      My advice to you is – take the ZXing code, open it, explore and find the answer. And most probably – they don’t give an access to captured image

  6. Andrew says:

    Hey,
    how can i access the ImgUri here?
    ” if (resultCode == RESULT_OK) {
    //use imageUri here to access the image

    • Andrey Chorniy says:

      it’s an attribute of your activity, you created it before started the Camera with intent

      //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
      imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

  7. dreamhost coupons says:

    This is actually what I was looking for. I am glad to come here! Thanks for sharing this information with us.

  8. Leandro Sinhorini says:

    Pictures are being saved in my photo gallery. It there any way to avoid it?

  9. mariano says:

    I’m beginning to develop apps on android (Ive been working 1 year in ios apps) and I need to develop a simple app that has a form with one or more fields that are pictures. I tried to make this example work with no luck. I put the first section of the code inside the onCreate method of my default activity. Then, I imported all required packages but I think there’s a lot of things I dont currently understand…so, can someone post a working example, a zip or a link to find out what I’m missing?

    I have found working pictures examples, but they does not follow this method of using the native camera activity, what is even more complex to understand.

    thanks!

  10. I rattling glad to find this internet site on bing, just what I was looking for : D also saved to favorites .

  11. vaishkhan says:

    can you tell me please how can i create an application which display the existing settings instead of camera…..thanks in advance

  12. pasha says:

    This is a very good post for working with camera.
    I see that you have generated a image name by yourself and then the camera saves the picture clicked with that name.
    I wanted to know if there is a way to get the path of the image stored by the Camera without giving the image name explicitly in this line “intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);”

    • Andrey Chorniy says:

      I don’t think it’s possible, however you may try to inspect the Camera code.
      As far as I remember – there is no way to find it that’s why I pass it here

      • pasha says:

        Andrey thanks for the reply. I had tried to use your code to invoke the default camera in my app, but I noticed that the camera comes back with a Save & Discard screen after the image is taken. This can actually be annoying for the users of my app. I tried to find a way to remove it, but seems like its not possible. Can you suggest me some work around for this….
        thank you

      • pasha says:

        Andrey thanks for the reply. I had tried to use your code to invoke the default camera in my app, but I noticed that the camera comes back with a Save & Discard screen after the image is taken. This can actually be annoying for the users of my app. I tried to find a way to remove it, but seems like its not possible. Can you suggest me some work around for this or building my own camera app is the only solution…
        thank you

  13. Naresh says:

    when i try to run the above code i am getting,

    CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE is undefined.

    how to solve this…?

  14. usman says:

    Hey Guys,
    I am getting nothing in imageURI. it is being returned as null. what could be wrong in this case?

    • Andrey Chorniy says:

      Do you mean you get null here ?
      imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

  15. Usman says:

    Hey Andrey,

    got it fixed thanks. there is a bug in android that is publisher dependent. in some phones it gives you data in the intent on activity result and in some phones you get the image in ImgeURI.

    http://stackoverflow.com/questions/1910608/android-action-image-capture-intent

  16. Joseph says:

    I’m able to start the camera activity just fine, but after taking a picture and returning to my app, I’m finding that my onActivityResult method is not being called. This is being done in through a TabActivity using an ActivityGroup to control what is contained in the tab.

    • Snap Point Labs says:

      Joseph….did you ever find out WHY this is ? I’m having the SAME problems! email me at snappointlabs@hotmail.com

      • Rootko says:

        It often does than when you have
        android:launchMode=”singleInstance”
        in your Manifest for that Activity

    • Amol says:

      I noticed that his code worked as expected on Sony Ericsson, Xperia (Android version 2.3.2) but did not call “onActivityResult” when running on Samsung Galaxy S 2 (Android version 2.3.3). Please guide if you have any more information on this.

  17. Somebody says:

    I did:

    String fileName = “/sdcard/testing.jpg”;
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, “testing.jpg”);
    values.put(MediaStore.Images.Media.DESCRIPTION,”Image capture by camera”);
    Uri imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    But the image taken by the camera is not there

  18. harmen says:

    nice post!

    shouldn’t
    “Toast.makeText(this, “Picture was not taken”, Toast.LENGTH_SHORT);”
    be
    “Toast.makeText(this, “Picture was not taken”, Toast.LENGTH_SHORT).show();”

  19. puspendu says:

    Thanks for the post.But i have a problem that whenever i take the picture neither it display nor it get saved in my gallery.Is something i missed?Although i am using emulator right now.

  20. puspendu says:

    i want to display the image in my application but it is unable to display and yeah you r correct it take time to show up in the gallery. and i also want to convert the URI to string so that i can attach the image as a mail. u u want i can send u my code. Thanks for replying me.

  21. kheang06 says:

    Could you give give me a full code of it? i have try with other example. but image i get always landscape. other way to check when device rotate portrait image to get from camera is portrait and when device rotate landscape image to get from camera is landscape. i have try for this lIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, 90); when i start activityforresult. but it look not working…plz help me. thank you

  22. kheang06 says:

    and how can we detect the image rotation for example image is 90 degree for 270 degree, when image get from camera. by using the ExifInterface class. i cannot check it. it working only get image from gallery. thank you.

  23. electronic document management…

    [...]Howto launch android camera using intents « Developer Notes[...]…

  24. kepler says:

    how I can get the real filename of the photo stored in the external media?? (ex: 2012_02_02 10.03.52.jpg) help. thanks.

  25. samir says:

    hii
    When I tried this out am getting this error

    ERROR/AndroidRuntime(511): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.android/com.android.builtin}: java.lang.NullPointerException

  26. vikram says:

    When i start camera app to get image it gives me rotated image on some devices and on some device it gives me in portrate mode. I need portrate image. How can i handle this.

  27. Simply want to say your article is as astonishing.
    The clearness for your submit is just nice and i can suppose you are knowledgeable on this subject.
    Well with your permission let me to clutch your feed to stay updated with approaching post.
    Thank you one million and please continue
    the rewarding work.

  28. kranthi says:

    I tried this code but it not works in some devices . built in camera was called in all devices but image not found in gallery.

    Can you tell me why its happen like that.

  29. kranthi says:

    Hi Andrey,

    I tried your sample code in galaxy y i got UnsupportedOperationException, it occuered in this line
    getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values).. bellow my log like this
    10-11 05:11:51.171: E/AndroidRuntime(30696): FATAL EXCEPTION: main
    10-11 05:11:51.171: E/AndroidRuntime(30696): java.lang.UnsupportedOperationException: Unknown URI: content://media/external/images/media
    10-11 05:11:51.171: E/AndroidRuntime(30696): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:146)
    10-11 05:11:51.171: E/AndroidRuntime(30696): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
    10-11 05:11:51.171: E/AndroidRuntime(30696): at android.content.ContentProviderProxy.insert(ContentProviderNative.java:408)
    10-11 05:11:51.171: E/AndroidRuntime(30696): at android.content.ContentResolver.insert(ContentResolver.java:604)

  30. zgamer108 says:

    my code is throwing exception at this line :

    //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
    imageUri = getContentResolver().insert(
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Please tell me what is going wrong.

  31. bianchi77 says:

    Hello Andrey,

    I can find the file in the gallery, can display it on My Tablet PC but can not display on my Smart Phone,

    The code :
    imageView.setImageURI(imageUri);

    I got Null Pointer Error on the smartphone,

    Why is it happened ?
    thanks

  32. apnea says:

    Hey there! I know this is somewhat off topic but I was wondering which blog platform are you using
    for this site? I’m getting tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be great if you could point me in the direction of a good platform.

  33. Krishna says:

    Nice Example, But i need a information that how to load camera with Front Mode. I tried with intent like this intent.putExtra(“android.intent.extras.CAMERA_FACING”, 1); but its not working.. Can any one suggest how to solve?

  34. Frances says:

    Hi there would yyou mind letting me knlw whicch weeb hoost you’re using?
    I’ve loaded yor boog in 3 cpmpletely different browsers andd I must say this blog lkads a loot faste then most.
    Cann you siggest a good hosting provider att a honest price?
    Kudos, I apprciate it!

  35. Andrey Chorniy says:

    Thanks for the notice! I think it depends on wordpress theme, will try to see if it works good for iPhone/Android. As for iPod, it’s not clear to me if it has a big enough share (in comparison to desktop/Iphone/adnroid browsers)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 31 other followers

%d bloggers like this: