首页 > 解决方案 > 为什么我没有从我的相机意图中收到任何图片(在 Android 中)

问题描述

我正在编写一个小程序,我想从我的相机中获取一张图片,将其显示在图像视图中(并稍后保存)。因此,我在按钮的 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);
}

我究竟做错了什么?帮助

标签: androidandroid-intentbitmapcamera

解决方案


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

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

推荐阅读