Android BitmapFactory.decodeFile 返回 null 即使图像存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3388898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BitmapFactory.decodeFile returns null even image exists
提问by stealthcopter
Saving the file:
保存文件:
FileOutputStream fo = null;
try {
fo = this.openFileOutput("test.png", Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(CompressFormat.PNG, 100, fo)
Loading the file:
加载文件:
String fname = this.getFilesDir().getAbsolutePath()+"/test.png";
Bitmap bMap = BitmapFactory.decodeFile(fname);
i.setImageBitmap(bMap);
The last line gives a null pointer exception, why is BitmapFactory.decodeFile returning null? I can verify that the file is getting saved correctly as I can pull it using adb and see the png displaying properly.
最后一行给出了空指针异常,为什么 BitmapFactory.decodeFile 返回空?我可以验证文件是否正确保存,因为我可以使用 adb 拉它并查看 png 正确显示。
回答by CommonsWare
If the NullPointerException
is directly on this line:
如果NullPointerException
直接在这条线上:
i.setImageBitmap(bMap);
i.setImageBitmap(bMap);
Then your problem is that i
is null
. Given that you're calling setImageBitmap(), I am guessing that i
is an ImageView
-- make sure your findViewById()
call is working.
那么你的问题i
是null
。鉴于您正在调用 setImageBitmap(),我猜这i
是一个ImageView
-- 确保您的findViewById()
调用正常工作。
Also, you should use the following to get fname
:
此外,您应该使用以下内容来获取fname
:
String fname=new File(getFilesDir(), "test.png").getAbsolutePath();
String fname=new File(getFilesDir(), "test.png").getAbsolutePath();
回答by Jeroen VL
When using the options parameter in the DecodeFile method be sure that the InJustDecodeBoundsproperty is set to falseor otherwise it will always return null. This can be set to true when you just want the file to be decoded but you don't need it further in your app/code. This way no extra memory needs to be allocated. See herefor an example.
在 DecodeFile 方法中使用 options 参数时,请确保将InJustDecodeBounds属性设置为false,否则它将始终返回 null。当您只想解码文件但在应用程序/代码中不需要它时,可以将其设置为 true。这样就不需要分配额外的内存。有关示例,请参见此处。