第一篇博客——BitmapFactory Unable to decode stream 问题解决

来源:互联网 发布:淘宝巴拉巴拉羽绒服 编辑:程序博客网 时间:2024/05/21 07:14

BitmapFactory Unable to decode stream 问题解决

第一篇博客,记录下遇到的错误吧。
今天做项目时从手机根目录读取图片文件并显示在ImageView中,习惯性的写下如下代码
File picture = new File(Environment.getExternalStorageDirectory(), "test.jpg");
String filepath = Uri.fromFile(picture).toString();
Bitmap bitmap = BitmapFactory.decodeFile( filepath);

运行时后提示错误BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/test.jpg: open failed: ENOENT (No such file or directory
查阅资料后发现并没有获取路径。
第一种修改:

File picture = new File(Environment.getExternalStorageDirectory(), "test.jpg");
Uri filepath = Uri.fromFile(picture);
Bitmap bitmap = BitmapFactory.decodeFile(filepath.getPath());

第二种修改:

bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(filepath));

通过获取数据流的方式比较安全。

从Android7.0后,直接使用本地真是Uri被认为是不安全的,会抛出一个FileUriExposedException异常。所以应该加个判断

 if (Build.VERSION.SDK_INT < 24) {         imageUri = Uri.fromFile(picture);    } else {        imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", picture); }

getUriForFile()接受3个参数,第一个参数要求传入Context对象,第二个可以是任意的唯一的字符串,第三个参数则是刚刚创建的file对象。
FileProvider是一种特殊的内容提供器,使用了和内容提供器类似的机制来对数据进行保护,可以选择性的将封装的Uri共享给外部,从而提高应用的安全性。

参考资料:http://stackoverflow.com/questions/21195899/bitmapfactory-unable-to-decode-stream
郭神的《第一行代码》

下一篇应该会写下retrofit2的初体验以及一些遇到的问题和解决方法。

1 0