为啥我没有收到来自我的相机意图的任何图片(在 Android 中)

Posted

技术标签:

【中文标题】为啥我没有收到来自我的相机意图的任何图片(在 Android 中)【英文标题】:Why do I not receive any Picture from my Camera-Intent (in Android)为什么我没有收到来自我的相机意图的任何图片(在 Android 中) 【发布时间】:2019-02-17 07:41:48 【问题描述】:

我正在编写一个小程序,我想从我的相机中获取一张图片,将其显示在图像视图中(并稍后保存)。因此,我在一个Button的onclick-Method中创建了一个Intent:

   File path;

    @Override
    public void onClick(View v) 
        path = new File(getFilesDir(), "Gallery/MyImages/");
        if (!path.exists()) path.mkdirs();

        File image = new File(path, "image_capture.jpg");
        Uri imageUri = FileProvider.getUriForFile(getApplicationContext(), CAPTURE_IMAGE_FILE_PROVIDER, image);

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        providePermissionForProvider(cameraIntent, imageUri);

        mCurrentPhotoPath = image.getAbsolutePath();
        startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);
    

    private void providePermissionForProvider(Intent intent, Uri uri) 
       List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) 
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    

当我点击按钮时,相机应用程序打开,我可以拍照。之后,我想在 onActivityResult-Method 的 Bitmap 中获取这张图片。但它不起作用:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);

        int targetW = main.getWidth();
        int targetH = main.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        Log.d("Facee", "afdadsfafdasfsfsfdsafdsafsdfdsafdsafdsafdsadsafdsadsf");
        main.setImageBitmap(bitmap);

我做错了什么? 帮助

【问题讨论】:

【参考方案1】:

我认为您没有获得图像的确切路径。使用这个:

File tempFile = File.createTempFile("camera", ".png", getExternalCacheDir());
mPath = tempFile.getAbsolutePath();
Uri uri = Uri.fromFile(tempFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

【讨论】:

【参考方案2】:

1 - 首先,您必须检查清单中是否有权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

和特点:

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />

如果你已经有了,你可以按照我的例子,让我们以简单的方式。

2 - 假设您的活动中有一个 ImageView 和一个 Button。 您将初始化您的组件并创建单击按钮功能。

private boolean isCamera = false;
private Uri fileUri;
private ImageView mImageView;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);

    mImageView = layout.findViewById(R.id.mImageView);
    Button mTakePhotoButton = layout.findViewById(R.id.mImageView);
    mTakePhotoButton.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
        final CharSequence[] items = "Take photo", "Cancel";

        isCamera = false;
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
        alertDialog.setTitle("Select Picture");
        alertDialog.setItems(items, new DialogInterface.OnClickListener() 
            @Override
            public void onClick(DialogInterface dialog, int item) 
                Intent intent;
                switch (item) 
                    case CAMERA:
                        isCamera = true;
                        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (intent.resolveActivity(getContext().getPackageManager()) != null) 
                            try 
                                File photoFile = Utils.createImageFile();
                                fileUri = Uri.fromFile(photoFile);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                                startActivityForResult(intent, 1);
                             catch (IOException ex) 
                                Log.e("PROJECT_TEST", e.getMessage());
                            
                        
                        break;
                    /*case GALLERY:
                        intent = new Intent();
                        // Show only images, no videos or anything else
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        // Always show the chooser (if there are multiple options available)
                        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)), imageBox);
                        break;*/
                    default:
                        dialog.dismiss();
                        break;
                
            
        );
        alertDialog.show();
        
    );

我的Utils.createImageFile,在设备目录下创建文件的函数:

public static File createImageFile() throws IOException 
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "img_" + timeStamp + ".png";
    File storageDir = new File(Environment.getExternalStorageDirectory(), "MyFolder");
    if (!storageDir.exists())
        storageDir.mkdirs();
    return new File(storageDir, imageFileName);

3 - 您将在 imageView 中将图像返回为 onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) 
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) 
        try 

            Bitmap selectedImage;
            if (!isCamera && data != null && data.getData() != null) 
                fileUri = data.getData();
            

            selectedImage = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), fileUri);

            if (selectedImage != null) 
                mImage1.setImageBitmap(selectedImage);
                String directory = fileUri.toString();
                Log.d("PROJECT_TEST", directory);
            
         catch (IOException e) 
            e.printStackTrace();
            Log.e("PROJECT_TEST", e.getMessage());
        
    

Obs:我使用的是 Fragment,如果你使用的是 Activity,你会将 getContext() 更改为 this

【讨论】:

【参考方案3】:

您的应用只需要存储权限。确保您拥有它 -

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

您的文件夹创建有问题。 使用这样的东西:

    path = new File(getExternalStorageDirectory()+ "/Gallery/MyImages/");
    if (!path.exists())path.mkdirs();

    File image = new File(path, "image_capture.jpg");
    Uri imageUri = FileProvider.getUriForFile(getApplicationContext(), CAPTURE_IMAGE_FILE_PROVIDER , image);

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

    mCurrentPhotoPath = image.getAbsolutePath();
    startActivityForResult(cameraIntent, ACTION_REQUEST_CAMERA);

注意点:inPurgeable 在 api 21 中已被弃用

【讨论】:

以上是关于为啥我没有收到来自我的相机意图的任何图片(在 Android 中)的主要内容,如果未能解决你的问题,请参考以下文章

在相机意图中显示叠加层

相机意图/活动 - 避免保存到画廊

从相机意图中获取像素的颜色

为啥我的 Apple Watch OS 应用只有在 iOS 应用处于活动状态时才能收到来自我的 iOS 应用的消息?

为啥使用相机意图捕获的图像会在 Android 上的某些设备上旋转?

在相机意图中显示图片库