如何知道图像是来自相机还是文件系统

时间:2015-11-11 11:21:37

标签: android android-intent android-camera

此代码曾用于以前版本的Android,因为来自onActivityResult的intent中的数据如果图像来自相机则返回null,如果从文件系统中选择图像,它将保留Uri。然而,在Lollipop上,相机意图也返回了Uri。如何知道图像是使用相机拍摄还是从文件存储/图库中选择?

这是我的代码:

private void openImageIntent() {

        // Determine Uri of camera image to save.
        final File root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "Klea" + File.separator);
        root.mkdirs();
        final String fname = getUniqueImageFilename();
        final File sdImageMainDirectory = new File(root, fname);
        outputFileUri = Uri.fromFile(sdImageMainDirectory);

        // Camera.
        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getActivity().getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(
                captureIntent, 0);
        for (ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent intent = new Intent(captureIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName,
                    res.activityInfo.name));
            intent.setPackage(packageName);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            cameraIntents.add(intent);
        }

        // Filesystem.
        final Intent galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

        // Chooser of filesystem options.
        final Intent chooserIntent = Intent.createChooser(galleryIntent,
                getString(R.string.chose_source));

        // Add the camera options.
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                cameraIntents.toArray(new Parcelable[] {}));

        startActivityForResult(chooserIntent, REQUEST_IMAGE_CAPTURE);
    }

    private static String getUniqueImageFilename() {
        // TODO Auto-generated method stub
        String fileName = "img_" + System.currentTimeMillis() + ".jpg";
        return fileName;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("reqCode", Integer.toString(requestCode));
        Log.d("resCode", Integer.toString(resultCode));
        Log.d("data", data.toString());
        getActivity();
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_IMAGE_CAPTURE) {
                final boolean isCamera;
                if (data == null) {
                    isCamera = true;
                } else {
                    final String action = data.getAction();
                    if (action == null) {
                        isCamera = false;
                    } else {
                        isCamera = action
                                .equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                }

                Uri selectedImageUri;
                if (isCamera) {
                    File file = new File(outputFileUri.toString());
                    Log.d("old file", file.toString());
                    String temp = file.toString().replace("file:", "");
                    Log.d("new file", temp);
                    selectedImageUri = Uri.parse(temp);
                } else {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};

                    Cursor cursor = getActivity().getContentResolver().query(
                            selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    selectedImageUri = Uri.parse(cursor.getString(columnIndex));
                    cursor.close();
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

首先,您无法保证。用户可以选择在其清单中声明 MediaStore.ACTION_IMAGE_CAPTURE 意图的任何应用,并且应用可能决定从文件系统中选择一张图片。

其次,请查看新的createChooser()方法,该方法需要IntentSender参数来返回最终用户的分析选项,请参阅this example (不幸的是,这是22岁及以上)

第三,你提供 outputFileUri MediaStore.EXTRA_OUTPUT - 这个文件有望由相机创建,但被文件系统选择器忽略;现在如果您只是在调用启动意图之前清理,您可以轻松检查该文件是否包含新图片。

我同意您的conclusion选择基于 data.dat content://media/… - &gt;文件,file:/… - &gt;相机)不可靠够了。

所以底线,简单但强大的区别可以这样做:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            final boolean isCamera = new File(outputFileUri.getPath()).length() > 0;
…