简体   繁体   English

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

[英]BitmapFactory.decodeStream returns null when reading from internal storage

I attempt to read images from the internal storage, when I decode FileInputStream, BufferedInputStream or a File using BitmapFactory I get null as a result: 我尝试从内部存储读取图像,当我使用BitmapFactory解码FileInputStream, BufferedInputStreamFile ,结果为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);
}

I tried all other answers I could find, but no luck so far. 我尝试了所有其他可以找到的答案,但是到目前为止还没有运气。

If you're running this code on Android 7 and you use BitmapFactory.decodeStream you need to reset InputStream every time you want yo use it again. 如果您在Android 7上运行此代码,并且使用BitmapFactory.decodeStream ,则每次想再次使用InputStream都需要重置InputStream For example I used it twice, first to get some metrics and then to decode into Bitmap. 例如,我使用了两次,首先获取一些度量,然后解码为Bitmap。 And it worked fine on all versions prior to Android 7. 而且它在Android 7之前的所有版本上都能正常运行。

Now I need to reset it, otherwise it returns null : 现在我需要重置它,否则它返回null

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

Resetting inputStream won't cause any bugs on older versions so it's safe to use. 重置inputStream不会在旧版本上引起任何错误,因此可以安全使用。

If it helped in your case - all credits to this guy: https://stackoverflow.com/a/41753686/5502121 如果这对您有帮助-此人的全部功劳: https : //stackoverflow.com/a/41753686/5502121

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM