【问题标题】:BitmapFactory.decodeFile returns null even image exists即使图像存在,BitmapFactory.decodeFile 也会返回 null
【发布时间】:2010-08-02 14:51:06
【问题描述】:

保存文件:

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”设置为什么,为什么它只有一个字符名称?
  • 是的,它已经关闭了。 i 是一个图像视图,它被设置为 null,因为我错误地引用了它。

标签: android bitmap imageview fileoutputstream


【解决方案1】:

如果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。这样就不需要分配额外的内存。示例见here

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多