位图空指针异常



我有从相机或图库中拾取图片的函数,但当我尝试在ImageView上设置时,它会返回位图上的Null指针。getWidth(),我也尝试使用decodeStream代替decodeFile,但我在路径变量中遇到错误,我该如何解决?我在Nexus 6上测试,顺便说一句,我的英语不好。

提前感谢!

@Override
    protected void onActivityResult(int requestCode, int resultCode,Intent data) {
        if (resultCode != RESULT_OK) return;
        Bitmap bitmap = null;
        String path = "";
        if (requestCode == PICK_FROM_FILE) {
            mImageCaptureUri = data.getData();
            path = getRealPathFromURI(mImageCaptureUri); //from Gallery
            if (path == null)
                path = mImageCaptureUri.getPath(); //from File Manager*/
            if (path != null)
                bitmap = BitmapFactory.decodeFile(path);
        } else {
            path = mImageCaptureUri.getPath();
            bitmap = BitmapFactory.decodeFile(path);
        }
        final double viewWidthToBitmapWidthRatio = (double) mImageView.getWidth() / (double) bitmap.getWidth();
        mImageView.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);
        mImageView.setImageBitmap(bitmap);
    }

这是日志:

FATAL EXCEPTION: main
 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/tmp_avatar_1450385165853.jpg: open failed: EACCES (Permission denied)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual  method 'int android.graphics.Bitmap.getWidth()' on a null object reference

图像似乎存在权限问题。

open failed: EACCES (Permission denied)

如果图像是动态生成的,然后保存到临时存储中,请确保您有权从该存储中读取。此外,请确保图像在保存/生成时可读。

还要检查以确保您的活动具有访问相机数据的权限

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

最后一件需要考虑的事情是使用API Level1中的"takePicture"方法。这是图片文档

这会将JPEG数据返回给回调,因为从文件URI加载原始字节,回调可能会绕过您正在执行的编码步骤。

最新更新