3

我使用 android 2.1,我想从相机意图结果中获取真实路径。我从 ACTION_IMAGE_CAPTURE Intent 中读取了 Get Path of image但它适用于 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();
    }
}
4

2 回答 2

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();
}
于 2013-03-10T14:10:52.033 回答
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();
}
于 2013-10-29T08:41:44.790 回答