从相机意图中检索内容Uri

时间:2012-04-10 14:46:24

标签: android android-camera

我正在为照相机拍摄一张Intent照片,如下所示:

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri myPhoto = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
    "the_photo.jpg"));

cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, myPhoto);
startActivityForResult(cameraIntent, INTENT_GET_PICTURE_FROM_CAMERA);

现在我想要显示此照片的缩略图。如果我存储“myPhoto”Uri,我可以准确地看到文件系统上的文件。但是,要使用Media Store API,我需要在内容Uri表单上使用Uri。无论如何从相机返回的意图中检索这个,如果不是,我如何将我的文件系统Uri转换为Android内容Uri。

注意,我知道我可以只取位图并对其进行解码,然后进行下采样。这不是我想要的。我可以查询所有缩略图,我发现它存在,所以我想从系统中获取它。

由于

2 个答案:

答案 0 :(得分:2)

我通过对项目执行媒体扫描解决了这个问题。从那里我可以获得内容Uri(下面的代码中处理程序的额外复杂性是因为我需要在UI线程处理视图时处理我的结果):

private Uri mCameraFilePath;
private Context mContext;
...

private void handlePictureFromCamera(Intent data) {

    MyMediaScannerClient client = new MyMediaScannerClient(
            mCameraFilePath.getPath(), new Handler(), new OnMediaScanned() {

        @Override
        public void mediaScanned(Uri contentUri) {
            //Here I have the content uri as its now in the media store
        }
    });
    MediaScannerConnection connection = new MediaScannerConnection(mContext, client);
    client.mConnection = connection;
    connection.connect();
}

private interface OnMediaScanned {
    public void mediaScanned(Uri contentUri);
}

/**
 * This is used to scan a given file (image in this case) to ensure it is added
 * to the media store thus making its content uri available. It returns the
 * content form Uri by means of a callback on the supplied handler's thread.
 */
private class MyMediaScannerClient implements MediaScannerConnectionClient {

    private final String mPath;
    private MediaScannerConnection mConnection;
    private final OnMediaScanned mFileScannedCallback;
    private final Handler mHandler;

    public MyMediaScannerClient(String path, Handler handler, OnMediaScanned fileScannedCallback) {
        mPath = path;
        mFileScannedCallback = fileScannedCallback;
        mHandler = handler;
    }

    @Override
    public void onMediaScannerConnected() {
        mConnection.scanFile(mPath, null);
    }

    @Override
    public void onScanCompleted(String path, final Uri uri) {

        mConnection.disconnect();
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                mFileScannedCallback.mediaScanned(uri);
            }
        });
    }
}

答案 1 :(得分:0)

我评论说,我需要类似的东西(获取“内容:// media / external / images / xxx”uri格式),你的解决方案效果很好。谢谢! 但我找到了一个更短的方法(也许它不适合你,但对其他人而言)。

使用与您相同的意图制定(第一篇文章),但使用“CAMERA_REQUEST”

在onActivityResult内部

    getContentResolver().notifyChange(mCapturedImageURI, null);
    ContentResolver cr = getContentResolver();
    Uri uriContent = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), photo.getAbsolutePath(), null, null));

以'content:// media / external / images / xxx'格式获取'uriContent'。