【问题标题】:BitmapFactory.decodeStream returns null when reading from internal storageBitmapFactory.decodeStream 从内部存储读取时返回 null
【发布时间】:2017-03-11 19:54:50
【问题描述】:

我尝试从内部存储中读取图像, 当我解码FileInputStream, BufferedInputStreamFile 使用BitmapFactory 我得到null 结果:

//mImages is an ArrayList of image file names, "a.jpg","b.jpg", etc.
//This is inside my custom adapter for returing ImageViews from mImages:

public View getView(int position, View ..., ViewGroup...){
Context base_context = MyApplication.getAppContext();

String currentImageFilename = mImages.get(position); //say this is "cat.jpg"

//after this line f = "/data/user/0/mobile.foo.bar/files/cat.jpg"
File f = base_context.getFileStreamPath(currentImageFilename);

Boolean ex = f.exists(); //returns true, inserted only for debugging as no 
//exception was thrown when decoding the bitmap and the result is null

BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(f));

Bitmap img = BitmapFactory.decodeStream(buffer); // img is null after this line
imageView.setImageBitmap(img);
}

我尝试了所有其他我能找到的答案,但到目前为止都没有运气。

【问题讨论】:

  • 尝试使用较小的图像。你拿了这么大的。
  • 请告知完整路径的值。你隐藏了你对所有这些功能所做的事情。您的 f.exist() 应该以这样一种方式使用,即如果 f 不存在则显示 toast 然后返回。现在 f.exists() 对流没有影响。
  • 感谢@greenapps .exists() 仅被插入,因此我可以向自己确认在调试时找到了文件,我不打算保留它。完整路径现在在编辑版本中,图像只有 18kb。
  • 移除 BufferedInputStream。
  • 仍然无法正常工作,也无法使用 decodeFile 或 decodeStream。然而,该文件存在。出了什么问题是完全不可见的,因为当我一步步深入调试时,我会深入到本机系统 API 解码器,我看不到进一步......

标签: java android android-studio


【解决方案1】:

如果您在 Android 7 上运行此代码并使用 BitmapFactory.decodeStream,则每次您希望再次使用它时都需要重置 InputStream。 例如,我使用了两次,第一次获取一些指标,然后解码为位图。它在 Android 7 之前的所有版本上都运行良好。

现在我需要重置它,否则返回null

BitmapFactory.decodeStream(iStream, null, options);
...
try {
    iStream.reset();
} catch (IOException e) {
    return null;
}
...
BitmapFactory.decodeStream(iStream, null, options);

重置 inputStream 不会导致旧版本出现任何错误,因此可以安全使用。

如果它对您的情况有所帮助 - 所有功劳归于这个人:https://stackoverflow.com/a/41753686/5502121

【讨论】:

  • 谢谢,在我的情况下没有必要,而是在保存图像时为图像创建了一个自定义目录,然后使用this.getDir("MyImagesFolder", Context.MODE_PRIVATE).getAbsolutePath() + File.Separator + "myimage.jpg"; 读取它们并且它有效。感谢您的帮助,它可能会帮助到这里的其他人。
  • 对于 Android >= 10 对我来说我必须在每次调用 decodeStream 之前重新调用 openInputStream 在尝试使用 2 个不同的选项时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 2017-03-10
  • 2015-02-25
  • 2011-05-23
  • 2012-11-24
相关资源
最近更新 更多