位图空指针异常

时间:2015-12-17 20:38:43

标签: android-studio bitmapimage bitmapfactory nexus6

我有从相机或图库中选择图片的功能但是当我尝试在ImageView上设置它在bitmap.getWidth()上返回Null指针时,我也尝试使用decodeStream而不是decodeFile但是我在路径变量中得到错误,我该怎么解决?我在Nexus 6上测试,BTW我的英语不好。

提前感谢!

@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

1 个答案:

答案 0 :(得分:1)

您的图片似乎存在权限问题。

open failed: EACCES (Permission denied)

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

同时检查以确保您的活动有权访问相机中的数据

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

最后要考虑的是使用API​​ Level1中的'takePicture'方法。 Here is the takePicture documentation

这会将JPEG数据返回给回调,这可能会绕过您从文件URI加载原始字节所采取的编码步骤。

相关问题