Android Capture Image from Camera and Gallery

Filed Under: Android

In this tutorial we’ll develop an application that picks an image from camera or gallery and display that in an ImageView.

Note: The below code works fine for pre-Android Nougat versions. For the latest working example check out the updated article.

Android Capture Image Overview

With the commence of Android Marshmallow, runtime permissions need to be implemented forefront.

Add the following permissions in the Android Manifest.xml file, above the application tag.

        android:required="false" />
        android:required="false" />
        android:required="false" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE"/>

By adding, Play Store detects and prevents installing the application on devices with no camera.

Intent is the standard way to delegate actions to another application.
To start the native camera the Intent requires android.provider.MediaStore.ACTION_IMAGE_CAPTURE.

To choose an image from gallery, the Intent requires the following argument : Intent.ACTION_GET_CONTENT.

In this tutorial we’ll be invoking an image picker, that lets us select an image from camera or gallery and displays the image in a circular image view and a normal image view. Add the following dependency inside the build.gradle file.
compile 'de.hdodenhof:circleimageview:2.1.0'

Android Image Capture Project Structure

android capture image from camera and gallery picker project

Android Capture Image Code

The layout for the activity_main.xml stays the same barring the icon change for the FAB button to @android:drawable/ic_menu_camera.

The content_main.xml is given below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""


            android:scaleType="centerCrop" />


        android:layout_centerHorizontal="true" />


The code for the is given below

public class MainActivity extends AppCompatActivity {

    Bitmap myBitmap;
    Uri picUri;

    private ArrayList permissionsToRequest;
    private ArrayList permissionsRejected = new ArrayList();
    private ArrayList permissions = new ArrayList();

    private final static int ALL_PERMISSIONS_RESULT = 107;

    protected void onCreate(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(;

        FloatingActionButton fab = (FloatingActionButton) findViewById(;
        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                startActivityForResult(getPickImageChooserIntent(), 200);

        permissionsToRequest = findUnAskedPermissions(permissions);
        //get the permissions we have asked for before but are not granted..
        //we will store this in a global list to access later.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (permissionsToRequest.size() > 0)
                requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);


    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == {
            return true;

        return super.onOptionsItemSelected(item);

     * Create a chooser intent to select the source to get image from.<br />
     * The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br />
     * All possible sources are added to the intent chooser.
    public Intent getPickImageChooserIntent() {

        // Determine Uri of camera image to save.
        Uri outputFileUri = getCaptureImageOutputUri();

        List allIntents = new ArrayList();
        PackageManager packageManager = getPackageManager();

        // collect all camera intents
        Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        List listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            Intent intent = new Intent(captureIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName,;
            if (outputFileUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

        // collect all gallery intents
        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        List listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
        for (ResolveInfo res : listGallery) {
            Intent intent = new Intent(galleryIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName,;

        // the main intent is the last in the list (fucking android) so pickup the useless one
        Intent mainIntent = allIntents.get(allIntents.size() - 1);
        for (Intent intent : allIntents) {
            if (intent.getComponent().getClassName().equals("")) {
                mainIntent = intent;

        // Create a chooser from the main intent
        Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");

        // Add all other intents
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));

        return chooserIntent;

     * Get URI to image received from capture by camera.
    private Uri getCaptureImageOutputUri() {
        Uri outputFileUri = null;
        File getImage = getExternalCacheDir();
        if (getImage != null) {
            outputFileUri = Uri.fromFile(new File(getImage.getPath(), "profile.png"));
        return outputFileUri;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Bitmap bitmap;
        if (resultCode == Activity.RESULT_OK) {

            ImageView imageView = (ImageView) findViewById(;

            if (getPickImageResultUri(data) != null) {
                picUri = getPickImageResultUri(data);

                try {
                    myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
                    myBitmap = rotateImageIfRequired(myBitmap, picUri);
                    myBitmap = getResizedBitmap(myBitmap, 500);

                    CircleImageView croppedImageView = (CircleImageView) findViewById(;

                } catch (IOException e) {

            } else {

                bitmap = (Bitmap) data.getExtras().get("data");

                myBitmap = bitmap;
                CircleImageView croppedImageView = (CircleImageView) findViewById(;
                if (croppedImageView != null) {





    private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {

        ExifInterface ei = new ExifInterface(selectedImage.getPath());
        int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return rotateImage(img, 90);
            case ExifInterface.ORIENTATION_ROTATE_180:
                return rotateImage(img, 180);
            case ExifInterface.ORIENTATION_ROTATE_270:
                return rotateImage(img, 270);
                return img;

    private static Bitmap rotateImage(Bitmap img, int degree) {
        Matrix matrix = new Matrix();
        Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
        return rotatedImg;

    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 0) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        return Bitmap.createScaledBitmap(image, width, height, true);

     * Get the URI of the selected image from {@link #getPickImageChooserIntent()}.<br />
     * Will return the correct URI for camera and gallery image.
     * @param data the returned data of the activity result
    public Uri getPickImageResultUri(Intent data) {
        boolean isCamera = true;
        if (data != null) {
            String action = data.getAction();
            isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);

        return isCamera ? getCaptureImageOutputUri() : data.getData();

    protected void onSaveInstanceState(Bundle outState) {

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("pic_uri", picUri);

    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        // get the file url
        picUri = savedInstanceState.getParcelable("pic_uri");

    private ArrayList findUnAskedPermissions(ArrayList wanted) {
        ArrayList result = new ArrayList();

        for (String perm : wanted) {
            if (!hasPermission(perm)) {

        return result;

    private boolean hasPermission(String permission) {
        if (canMakeSmores()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
        return true;

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)

    private boolean canMakeSmores() {
        return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {

            case ALL_PERMISSIONS_RESULT:
                for (String perms : permissionsToRequest) {
                    if (hasPermission(perms)) {

                    } else {


                if (permissionsRejected.size() > 0) {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
                            showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                                                //Log.d("API123", "permisionrejected " + permissionsRejected.size());

                                                requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);




There are a lot of inferences to be drawn from the code above.

  • We need to ask for the Camera runtime permissions when the user starts the activity.
  • As we are starting the intent to get some result back, we need to call startActivityForResult with the relevant arguments
  • Instead of using a dialog to separately call the Intents for Camera and Gallery, we’ve used a method getPickImageChooserIntent() that creates a single chooser intent for all the camera and gallery intents(note the documents intent). Intent.EXTRA_INITIAL_INTENTS is used to add the multiple application intents at one place
  • For the camera intent, MediaStore.EXTRA_OUTPUT is passed as an extra to specify the image storage path. Without this you’ll be returned only a small resolution image.
  • The URI path for the image returned by camera is fetched inside the method getCaptureImageOutputUri().
  • The onActivityResult essentially returns a URI to the image. Some devices do return the bitmap as data.getExtras().get("data");.
  • When an image is clicked, the camera screen while returning restarts the activity thereby causing the URI stored from the method getCaptureImageOutputUri() to become null.
    Hence it’s essential that we store and restore that URI using onSaveInstanceState() and onRestoreInstanceState().
  • The bitmap is retrieved from the URI in the following line of code.
    myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
  • Devices like Samsung galaxy are known to capture the image in landscape orientation. Retrieving the image and displaying as it is can cause it to be displayed in the wrong orientation. Hence we’ve called the method rotateImageIfRequired(myBitmap, picUri);
  • ExifInterface is a class for reading and writing Exif tags in a JPEG file or a RAW image file.
  • In the end we call the method getResizedBitmap() to scale the bitmap by width or height(whichever is larger) and set the image to the image view using setImageBitmap.

The output of the application in action is given below. Note: To capture and display an image from camera you’ll need to run the application on a smartphone for obvious reasons.

android capture image

This brings an end to this tutorial. You can download the Android project for Image Capture from the link below.


  1. Narayan Semwal says:

    Dear Sir ,
    Can you share working code to support android 11 (R) and above for capturing image

  2. Shrini jaiswal says:

    Can you share working code to support android 10 and above for capturing image and video ?
    The above codde is not working Android 10 and above

  3. kshitija says:

    image is rotating in 0ne plus phone.

  4. Karan says:

    App stuck in Android 10 any solution do you have please update it

  5. Shailesh Vishwase says:

    Nice documentation. but I am looking for help to access SD card photos using Android 10(API 29). I have tried a lot but didn’t get success. Each time I got the path ‘Document/6AE7-160C:download/5528-i-love-you-poems.jpg’. Will you please help me to solve this?

  6. MuayinKei says:

    Not save image

  7. Panneer says:

    Dear Sir,

    Android Version 9 (Pie) Device Camera Not Working in this Code

    Can’t Get onActivityResult Debug area

    Pls Help me

    1. ANUPAM CHUGH says:

      try android.provider.MediaStore.ACTION_IMAGE_CAPTURE

  8. Meghana Shetty says:

    OnActivityResult , camera is always false even though a picture is clicked. Intent action does not match MediaStore.ACTION_IMAGE_CAPTURE

  9. Harish says:

    Camera image is not saving in external storage.
    and Camera image is not set to CircleImageView

  10. sunil sharma says:

    on select image from gallery it gives the error in logcat as
    05-14 16:45:20.578 E/picUri is: content://
    05-14 16:45:20.856 W/ExifInterface: Invalid image. /raw/storage/emulated/0/DCIM/Camera/IMG_20180511_121705.jpg: open failed: ENOENT (No such file or directory)
    The problem is i want to upload image to server,on select image from camera or gallery intent ,image uploaded successfully on camera intent but image select from gallery did not work.

  11. Omkar Mahadik says:

    if anyone’s stuck above 6.0
    just make a new method and return it.
    public Uri getPickImageResultUri(Intent data) {
    boolean isCamera = true;
    if (data != null) {
    String action = data.getAction();
    isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
    return isCamera ? getCaptureImageOutputUri() : getImageUriFromGallery(data.getData());

    private Uri getImageUriFromGallery(Uri uri) {
    Uri selectedImage = uri;
    String[] filePathColumn = { MediaStore.Images.Media.DATA };

    Cursor cursor = getContentResolver().query(selectedImage,
    filePathColumn, null, null, null);

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    return Uri.fromFile(new File(picturePath));

  12. Sohel says:

    Need to add


    Excellent Tutorial for Image Picker

  13. Jonathan says:

    Nice Work but in android 6.0 don´t work get the image from gallery.

    If you can give me a solution

    1. unique shakya says:

      i am getting the same problem. please do contact me if you find a solution.

    2. tun says:

      I ve been unable to select image from gallery too.Please have you found a solution

      1. tun says:

        please has anyone got it work on 6.0

  14. Mauricio says:

    Thank you, excellent tutorial.

  15. Raheel says:

    when i taps on gallery the app stop working and closed.

  16. Santanu Mukherjee says:

    Hey, It seems to be good working tutorial of image picker. Thumbs for your effort.

  17. VIvek says:

    Nice work…!!

  18. Sujit says:

    You will get OOM in some devices. Just do getResizedBitmap() before rotateImageIfRequired() . It will fix OOM .

  19. emmy says:

    Nice one thumbs up

  20. sagar says:

    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content