如何从相机图像意图路径?(How to get image path from camera int

2019-07-21 06:31发布

我与Android 2.1的工作,我想从相机意图的结果真实路径。 我读从ACTION_IMAGE_CAPTURE意图获取图像的路径 ,但它是为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();
    }
}

Answer 1:

它上面的代码工作在一些移动,但不会在三星手机在我的情况,所以我实现的公共逻辑适用于所有设备。

当我捕捉摄像头照片,所以我用游标实现逻辑和迭代光标并获得其从相机拍摄的最后一张照片的路径。

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();
}


Answer 2:

通过@TGMCians给出的答案工作,但我能在下面进一步凑合它

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();
}


文章来源: How to get image path from camera intent?