How to get image path from camera intent?

2020-02-29 11:31发布

问题:

i work with android 2.1 , and i want to get real path from Camera intent result. I read Get Path of image from ACTION_IMAGE_CAPTURE Intent but it is for android 2.2.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == CAMERA_RESULT)
    {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        imv.setImageBitmap(thumbnail);
         Uri selectedImageUri = data.getData();
         String path = getRealPathFromURI(selectedImageUri);
    }
}

private String getRealPathFromURI(Uri contentUri)
{
    try
    {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    catch (Exception e)
    {
        return contentUri.getPath();
    }
}

回答1:

Its above code works in some mobile but does not work in samsung mobile in my case so I implemented the common logic for all devices.

When I capture the photo from camera so I implement a logic using Cursor and iterate the cursor and get the last photo path which is capture from camera.

Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
    do {
        uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
        photoPath = uri.toString();
    }while(cursor.moveToNext());
    cursor.close();
}


回答2:

The answer given by @TGMCians works but i was able to improvise it further as below

Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToLast()){
    Uri fileURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
    String fileSrc = fileURI.toString();
    cursor.close();
}