2010-08-02 135 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

相關問題