如何从相机意图获取图像路径?

时间:2013-03-10 13:20:22

标签: android image android-intent camera

我使用Android 2.1,我想从Camera意图结果获得真正的路径。我读了Get Path of image from ACTION_IMAGE_CAPTURE Intent,但它适用于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();
    }
}

2 个答案:

答案 0 :(得分:7)

  

上面的代码适用于某些手机,但在我的情况下不适用于三星手机,所以我为所有设备实现了通用逻辑。

当我从相机捕捉照片时,我使用光标实现逻辑并迭代光标并获取从相机捕获的最后一个照片路径。

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

答案 1 :(得分:5)

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