从内部存储读取时,BitmapFactory.decodeStream返回null

时间:2017-03-11 19:54:51

标签: java android android-studio

我尝试从内部存储中读取图像, 当我解码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);
}

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

1 个答案:

答案 0 :(得分:2)

如果您在 Android 7 上运行此代码并使用BitmapFactory.decodeStream,则每次需要重新使用时都需要重置InputStream。 例如,我使用了两次,首先获得一些指标,然后解码为Bitmap。它在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