Getting path of captured image in Android using camera intent
Asked Answered
A

6

56

I have been trying to get path of captured image in order to delete image. Found many answers on StackOverflow but none of them are working for me. I got the following answer:

private String getLastImagePath() {
    final String[] imageColumns = { MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATA };
    final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
    Cursor imageCursor = POS.this.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
            null, null, imageOrderBy);
    if (imageCursor.moveToFirst()) {
        // int id = imageCursor.getInt(imageCursor
        // .getColumnIndex(MediaStore.Images.Media._ID));
        String fullPath = imageCursor.getString(imageCursor
                .getColumnIndex(MediaStore.Images.Media.DATA));
        return fullPath;
    } else {
        return "";
    }
}

This code works in Samsung tab but doesn't work in Lenovo tab and i-ball tab. So, can anyone help me find another solution to do the same? Any help will be appreciated. Thank you.

This is my onActivityResult:

if (requestCode == CmsInter.CAMERA_REQUEST && resultCode == RESULT_OK) {
    //Bitmap photo = null;
    //photo = (Bitmap) data.getExtras().get("data");

    String txt = "";
    if (im != null) {
        String result = "";
        //im.setImageBitmap(photo);
        im.setTag("2");
        int index = im.getId();
        String path = getLastImagePath();
        try {
            bitmap1 = BitmapFactory.decodeFile(path, options);
            bitmap = Bitmap.createScaledBitmap(bitmap1, 512, 400, false);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] bytData = baos.toByteArray();
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            result = Base64.encode(bytData);
            bytData = null;
        } catch (OutOfMemoryError ooM) {
            System.out.println("OutOfMemory Exception----->" + ooM);
            bitmap1.recycle();
            bitmap.recycle();
        } finally {
            bitmap1.recycle();
            bitmap.recycle();
        }
    }
}
Alcibiades answered 2/12, 2013 at 11:29 Comment(1)
stackoverflow.com/a/15432979Varitype
M
122

Try like this

Pass Camera Intent like below

    Intent intent = new Intent(this);
    startActivityForResult(intent, REQ_CAMERA_IMAGE);

And after capturing image Write an OnActivityResult, as exhibited by the following code copied from the Stack Overflow answer Get file path of image on Android

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
    
    
            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
            Uri tempUri = getImageUri(getApplicationContext(), photo);
    
            // CALL THIS METHOD TO GET THE ACTUAL PATH
            File finalFile = new File(getRealPathFromURI(tempUri));
    
            System.out.println(mImageCaptureUri);
        }  
    }
    
    public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = Images.Media.insertImage(inContext.getContentResolver(), inImage,
"Title", null);
        return Uri.parse(path);
    }
    
    public String getRealPathFromURI(Uri uri) {
        String path = "";
        if (getContentResolver() != null) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                path = cursor.getString(idx);
                cursor.close();
            }
        }
        return path;
    } ```

And check log.

Edit:

Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri method:


    public Uri getImageUri(Context inContext, Bitmap inImage) {
        Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
        return Uri.parse(path);
    }

The other method Compresses the file. You can adjust the size by changing the number 1000,1000

Mathews answered 2/12, 2013 at 11:55 Comment(17)
I don't have any cameraActivity classAlcibiades
android camera intent is like Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);Alcibiades
Check my updated answer,you don't need to write that class name @AlcibiadesMathews
what about CameraActivity.EXTRA_IMAGE_PATHAlcibiades
Intent intent = new Intent(); startActivityForResult(intent, CmsInter.CAMERA_REQUEST); I'm getting ActivityNotFoundException.Alcibiades
what does "mImageCaptureUri" stands for??Dorree
Error:(81, 27) error: cannot find symbol method getImageUri(Context,Bitmap)Bickerstaff
(Bitmap) data.getExtras().get("data") gives me temp file therefore path is also of temp Image. How can I get orignal file?Saltine
the above code make thumbnail image.how can i get full size image from above code?Dashed
MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "data", null); this line gives me nullUhhuh
is it a thumbnail or full size image from above code?Wanderoo
the above code make thumbnail image @ArthurZhixinLiuMathews
did any one got any fix for this thumbnail image?And
Hi, For me path getting null can anybody help here meAlkyne
in getImageUri, I get empty pathPetrinapetrine
@DIRTYDAVE glad to help :)Mathews
I seen lot of device specific problems coming in android Gallery and Camera image picker now a days. The best is to implement any third party good library . github.com/nguyenhoanglam/ImagePicker i am using this and working great across device. It also work for android 10Mathews
E
16

There is a solution to create file (on external cache dir or anywhere else) and put this file's uri as output extra to camera intent - this will define path where taken picture will be stored.

Here is an example:

File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(getActivity().getExternalCacheDir(), 
                String.valueOf(System.currentTimeMillis()) + ".jpg");
        fileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {

                //do whatever you need with taken photo using file or fileUri

            }
        }
    }

Then if you don't need the file anymore, you can delete it using file.delete();

By the way, files from cache dir will be removed when user clears app's cache from apps settings.

Epsilon answered 20/5, 2016 at 14:46 Comment(0)
D
5

Try this method to get path of original image captured by camera.

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

Distract answered 9/1, 2016 at 7:12 Comment(2)
what if there is no external storageUhhuh
I do get very bad quality using thisYenta
J
5

Here I updated the sample code in Kotlin. Please note on Nougat and above version Uri.fromFile(file) is not working and it crashes the app for that need to implement FileProvider which is safest way to send files from intent. For implementing this refer this answer or this article

private fun takePhotoFromCamera() {
        val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
        if (isDeviceSupportCamera) {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
                        System.currentTimeMillis().toString() + ".jpg")
//            fileUri = Uri.fromFile(file)
                fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                }
                startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
            }

        } else {
            Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
        }
    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
             if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
                realPath = file?.path
                 //do what ever you want to do
            }
    }
}
Judyjudye answered 2/3, 2018 at 12:20 Comment(0)
B
3

Please refer to Google Documentation: Camera - Photo Basics

Brandling answered 1/5, 2019 at 7:48 Comment(0)
M
-1

try this

String[] projection = { MediaStore.Images.Media.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(mCapturedImageURI, projection,
                    null, null, null);
            int column_index_data = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            image_path = cursor.getString(column_index_data);
            Log.e("path of image from CAMERA......******************.........",
                    image_path + "");

for capturing image:

    String fileName = "temp.jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    mCapturedImageURI = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
    values.clear();
Michaeline answered 2/12, 2013 at 11:43 Comment(2)
from where do i get the mCapturedImageURI ?Alcibiades
i tried it but then i'm getting null pointer on below line photo = (Bitmap) data.getExtras().get("data");Alcibiades

© 2022 - 2024 — McMap. All rights reserved.