2010-08-02 138 views
9

保存文件:BitmapFactory.decodeFile返回null即使图像中存在

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正确显示。

+0

你关闭了文件输出流吗?什么是“我”设置,为什么它有一个单一的字符名称? – Douglas 2010-08-02 14:53:40

+0

是的,它已关闭。我是一个图像视图,它被设置为空,因为我不正确地引用它。 – stealthcopter 2010-08-02 16:09:32

回答

18

如果NullPointerException直接在这一行:

i.setImageBitmap(BMAP);

那么你的问题是,inull。鉴于你打电话给setImageBitmap(),我猜测i是一个ImageView - 确保你的findViewById()调用正在工作。

此外,您应该使用以下方法来获取fname

字符串FNAME =新的文件(getFilesDir(), “test.png”)getAbsolutePath();

2

当使用在DecodeFile方法的选项参数可以肯定的是,InJustDecodeBounds属性设置为否则就总是返回null。如果您只是想要解码文件,但在应用程序/代码中不需要它,则可将其设置为true。这样不需要分配额外的内存。一个例子见here

相关问题