无法将从相机拍摄的图像加载到ImageView中

4
我能够将相机拍摄的图像保存到内部存储中,但是我无法将其加载到ImageView中,而且ImageView保持为空白。我已经阅读了所有相关的建议,但未找到合适的解决方案。请查看下面的相关代码,任何帮助都将非常感激,因为我已经在苦苦挣扎几天了...
清单权限:
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

在XML中使用ImageView:

<ImageView
    android:id="@+id/recipeImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="10dp"
    android:layout_weight="1"
    android:background="@color/backgroundColorHomeBottomLayout"
    android:padding="30dp" />

相关活动:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_IMAGE_CAPTURE) {
        if (resultCode == RESULT_OK) {
            setPic();
            //mImageView.setImageURI(fileUri);
        }
        else if (resultCode == RESULT_CANCELED) {
            /** user cancelled Image capture */
            Toast.makeText(this,
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            /** failed to capture image */
            Toast.makeText(this,
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

/** Internal memory methods */
private void launchCameraIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        /** Ensure that there's a camera activity to handle the intent */
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        /** Create the File where the photo should go */
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "v3.com.mycookbook5.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

/** return a unique file name for a new photo using a date-time stamp */
private File createImageFile() throws IOException {
    /** Create an image file name */
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
    /** Save a file: path for use with ACTION_VIEW intents */
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

private void setPic() {
    // Get the dimensions of the View
    int targetW = mImageView.getWidth();
    int targetH = mImageView.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);
    mImageView.setImageBitmap(bitmap);
}

日志:

07-03 12:56:07.188 3950-16091/? E/Drive.UninstallOperation: Package still installed v3.com.mycookbook5
07-03 12:56:35.350 19680-19680/v3.com.mycookbook5 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/Android/data/v3.com.mycookbook5/files/Pictures/JPEG_20160703_125629_-664091716.jpg: open failed: ENOENT (No such file or directory)
07-03 12:56:35.350 19680-19680/v3.com.mycookbook5 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/Android/data/v3.com.mycookbook5/files/Pictures/JPEG_20160703_125629_-664091716.jpg: open failed: ENOENT (No such file or directory)

请发布设备日志(应用程序的日志,甚至不过滤应用程序名称)。没有例外吗?在其他设备上行为是否相同? - FunkSoulBrother
日志已附上,希望是正确的,我是 Android 新手。我只在 One Plus One 上进行了测试。 - Napo
5个回答

1
问题已解决。为了帮助他人,以下是应该执行的步骤:
  1. Downgrade targetSdkVersion on build.gradle from 23 --> 22, to avoid permission issues.
  2. Add the following code to launchCameraIntent() method:

    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    
  3. Change setPic method as follow:

        Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getPath());
        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(rotatedBitmap, 200, 150 ,false);
        mImageView.setImageBitmap(scaledBitmap);
    

1
我认为你的问题是因为你没有给图片足够的时间保存到SD卡,代码在完全保存之前就开始寻找它,因此你需要提供一个延迟处理程序来确保图片成功保存,同时使用以下方法获取图片路径:
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            setPic();
        }
    }, 750);

获取SD卡中的图像:

File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image_name.jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);

public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) 
{ 

    /*
     * here you set all of your bmOptions specs
     */

    return BitmapFactory.decodeFile(path, bmOptions);
}

谢谢Muhammed,实际上我将图像保存到了内部存储。您的解决方案是否也适用于此? - Napo
首先,尝试延迟处理程序的方式。 - Muhammed Refaat

0

我认为你可能会得到一个零大小的图像,因为尝试将其调整为imageView大小(如果尚未呈现,则可能为零大小)。

尝试在没有任何操作的情况下加载图像,并在成功后更改代码以减少内存消耗,逐步优化,直到获得最佳结果。

祝你好运。


谢谢您的帮助,但我只是在Android方面迈出了第一步,不确定该如何做。 - Napo

0
你需要从意图中获取额外的数据,对吧?'onActivityResult' 会将结果代码和带有额外数据(即图片位图)的结果返回给你的活动,你应该以任何你选择的方式传递这些数据到你的 setPic 方法中。
为了获取位图照片,你可以使用下面的代码。
if (requestCode == REQUEST_IMAGE_CAPTURE) { 
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
}

0

尝试这段代码适用于棉花糖系统

Uri imageFileUri = data.getData();

 final Bitmap bitmap = getBitmapFromUri(imageFileUri);

 private Bitmap getBitmapFromUri(Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                getLocalContext().getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }



    @Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_IMAGE_CAPTURE) {
        if (resultCode == RESULT_OK) {

            //mImageView.setImageURI(fileUri);
 Uri imageFileUri = data.getData(); 
 final Bitmap bitmap = getBitmapFromUri(imageFileUri);
setPic(bitmap);  
        } 
        else if (resultCode == RESULT_CANCELED) {
            /** user cancelled Image capture */ 
            Toast.makeText(this,
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else { 
            /** failed to capture image */ 
            Toast.makeText(this,
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        } 
    } 
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接