BitmapFactory.decodeFile returns null even image exists

 ̄綄美尐妖づ 提交于 2019-11-30 08:58:09

问题


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.


回答1:


If the NullPointerException is directly on this line:

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.

Also, you should use the following to get fname:

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




回答2:


When using the options parameter in the DecodeFile method be sure that the InJustDecodeBounds property is set to false or 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 here for an example.



来源:https://stackoverflow.com/questions/3388898/bitmapfactory-decodefile-returns-null-even-image-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!