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

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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值