简体   繁体   English

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

[英]How to know if image is from camera or file system

This code used to work on previous versions of Android, because the data from the intent in onActivityResult, would return null if the image came from the camera, and it would hold a Uri if the image was selected from the file system. 此代码曾用于以前版本的Android,因为来自onActivityResult的intent中的数据如果图像来自相机则返回null,如果从文件系统中选择图像,它将保留Uri。 However, on Lollipop, the camera intent is also returning a Uri. 然而,在Lollipop上,相机意图也返回了Uri。 How do I know whether the image was taken with the camera or was selected from the file storage/gallery? 如何知道图像是使用相机拍摄还是从文件存储/图库中选择?

Here is my code: 这是我的代码:

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

First of all, there can be no guarantee for you. 首先,您无法保证。 The user can choose any app that declares the MediaStore.ACTION_IMAGE_CAPTURE intent in its manifest, and the app may decide to pick a picture from file system. 用户可以选择在其清单中声明MediaStore.ACTION_IMAGE_CAPTURE意图的任何应用程序,并且应用程序可能决定从文件系统中选择图片。

Second, have a look at the new createChooser() method that takes an IntentSender parameter to return the end user's choice for you to analyze, see this example (unfortunately, this is 22 and up) . 其次,看看新的createChooser()方法,该方法采用IntentSender参数返回最终用户的选择供您分析,请参阅此示例 (不幸的是,这是22及以上)

Third, you provide outputFileUri as MediaStore.EXTRA_OUTPUT - this file will be hopefully created by camera, but ignored by the file system picker; 第三,你提供outputFileUri作为MediaStore.EXTRA_OUTPUT - 这个文件有望由摄像机创建,但被文件系统选择器忽略; now if you only clean up before calling launching the intent, you can easily check whether the file contains a new picture. 现在如果你只是调用启动意图之前清理,你可以轻松检查文件是否包含新图片。

I agree with your conclusion that choosing based on data.dat ( content://media/… -> file, file:/… -> camera) is not reliable enough. 我同意你的结论 ,选择基于data.datcontent://media/… - >文件, file:/… - >相机)是不够可靠的。

So the bottom line, the easy but robust distinction can be made like this: 因此,底线,简单而强大的区别可以这样做:

@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;
…

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM