【问题标题】:Unable to decode stream无法解码流
【发布时间】:2016-12-19 05:23:30
【问题描述】:

我想使用图像文件的绝对路径将图像保存到位图中,下面是我的代码:

Log.d("PhotoPath", selected.getImagePath());
File file = new File(selected.getImagePath());
if(file.exists())
{
    Log.d("File", "Exist");
    Bitmap d = new BitmapDrawable(getResources(), selected.getImagePath()).getBitmap();
    int nh = (int) (d.getHeight() * (512.0 / d.getWidth()));
    Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
    iv_Photo.setImageBitmap(scaled);
}
else
    Log.d("File", "Not exist");

以下是我的输出,包括异常:

D/PhotoPath: /storage/emulated/0/DCIM/POEMS/JPEG_20161214_170251_1637243168.jpg
D/File: Exist
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/DCIM/POEMS/JPEG_20161214_170251_1637243168.jpg (Permission denied)
W/BitmapDrawable: BitmapDrawable cannot decode /storage/emulated/0/DCIM/POEMS/JPEG_20161214_170251_1637243168.jpg

有什么问题?我确实在 Manifest 中添加了WRITE_EXTERNAL_STORAGE 权限。

【问题讨论】:

  • 无法解码 - 这个错误是因为如果你尝试解码一个文件,你应该加载 file.getAbsolutePath() ,它应该给 android 类似 file:/storage/emulated/0/DCIM/POEMS /JPEG_20161214_170251_1637243168.jpg ,所以这里 file:/ 丢失了所以它不会解码图像
  • 你注意到了吗 - Permission denied
  • 你也应该指定这个权限。
  • 如果您的目标是 API 23,您必须在运行时请求权限。看看这个 - developer.android.com/training/permissions/requesting.html
  • @MonishKamble 谢谢你,问题是我没有在运行时请求权限。

标签: android filenotfoundexception


【解决方案1】:

请看下面,你需要解码文件路径然后你会得到位图。

Log.d("PhotoPath", selected.getImagePath());
File file = new File(selected.getImagePath());
if(file.exists())
{
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
else
    Log.d("File", "Not exist");

【讨论】:

  • 问题是由于在 logcat 消息中看到的运行时权限造成的。
  • 请将目标版本设置为 21,然后运行您的应用程序。
  • 为什么要降低目标版本?那不是解决方案。解决方案是实现运行时权限。
  • 那么你需要实现版本条件来获取上面这些代码的权限,然后在权限访问块上你可以做到这一点。否则我已经告诉你你需要做什么了。
  • 正如 OP 所评论的,问题是由于运行时权限造成的。图像解码代码没有错。这不是一个有效的答案。
猜你喜欢
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 2017-07-23
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多