BitmapFactory.decodeFile返回null,即使图像存在。

11

保存文件:

FileOutputStream fo = null; 
try { 
        fo = this.openFileOutput("test.png", Context.MODE_WORLD_READABLE); 
} catch (FileNotFoundException e) { 
        e.printStackTrace(); 
} 
bitmap.compress(CompressFormat.PNG, 100, fo)

加载文件:

String fname = this.getFilesDir().getAbsolutePath()+"/test.png"; 
Bitmap bMap = BitmapFactory.decodeFile(fname);
i.setImageBitmap(bMap);
最后一行会导致空指针异常,为什么 BitmapFactory.decodeFile 返回 null?我可以验证文件已正确保存,因为我可以使用 adb 拉取它并查看 png 正确显示。

您是否已关闭文件输出流?"i" 设置为什么,为什么它只有一个字符的名称? - Douglas
是的,它已经关闭了。我是一个图像视图,因为我引用不正确,所以被设置为空。 - stealthcopter
2个回答

20
如果 NullPointerException 出现在这行代码上:

i.setImageBitmap(bMap);

那么你的问题可能是因为 inull。鉴于你正在调用 setImageBitmap(),我猜测 i 是一个 ImageView,确保你的 findViewById() 调用有效。
此外,您应该使用以下方法获取 fname:

String fname = new File(getFilesDir(), "test.png").getAbsolutePath();


2

使用DecodeFile方法中的options参数时,请确保InJustDecodeBounds属性设置为false,否则它将始终返回null。当您只想解码文件但不需要在应用程序/代码中进一步使用它时,可以将其设置为true。这样就不需要分配额外的内存。请参见此处的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接