Bitmap从BitmapFactory.decodeFile(filename)返回null

Sum*_*tel 32 android

当我调用此函数时,图像视图中没有bitmapFactory.decodefile(filename)显示null的图像 ..请帮忙.

这是我的代码:

public Bitmap ShowImage(String imageName,String userImageName ) 
{

    File sdcard_mainDirectory = new File(Environment.getExternalStorageDirectory(),"UserImages").getAbsoluteFile();

    File file = new File(sdcard_mainDirectory, userImageName).getAbsoluteFile();

    if (file != null) {

        try {

            String imageInSD = "/sdcard/UserImages/"+userImageName;

            Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);

            return bitmap;

        }
        catch (Exception e) {

            e.printStackTrace();
        }

    }

    return null;

}
Run Code Online (Sandbox Code Playgroud)

kal*_*a c 38

嗨,这是null因为可能是图像大小很大并且获得异常请检查您的日志,如果是,则查看是否有任何错误的outofmemory位图然后使用选项:

BitmapFactory.Options options;

try {
  String imageInSD = "/sdcard/UserImages/" + userImageName;
  Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
  return bitmap;
} catch (OutOfMemoryError e) {
  try {
    options = new BitmapFactory.Options();
    options.inSampleSize = 2;
    Bitmap bitmap = BitmapFactory.decodeFile(imageInSD, null, options);
    return bitmap;
  } catch(Exception excepetion) {
    Log.e(excepetion);
  }
}
Run Code Online (Sandbox Code Playgroud)


use*_*305 10

你为什么要这样做 String imageInSD ="/ sdcard/UserImages /"+ userImageName;

我想如果你得到一个.png文件,那么,

 Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)

注意:还要检查该位置是否存在Android支持的图像文件.


ina*_*ruk 8

这很简单:您的文件不是Android的Bitmap实现不支持的图像或图像,或者您的路径无效.


请参阅以下文档BitmapFactory.decodeFile(String file):

返回
生成的解码位图,如果无法解码,则返回 null.


通常,当位图无法解码时,会将某些日志打印到logcat.仔细检查它们.

  • “通常当位图无法解码时,一些日志会打印到 logcat。仔细检查它们。” 这个关键句子是我的,谢谢:) (2认同)

Jer*_* VL 8

请确保在您的选项(BitmapFactory.Options)中将InJustDecodeBounds设置为false,否则它将返回null.当您只想解码文件但在代码中不需要它时,可以将其设置为true.这样就不需要分配额外的内存.请参阅此处以获取更多解释


eya*_*yal 7

尝试添加SD卡访问权限READ_EXTERNAL_STORAGE和/或WRITE_EXTERNAL_STORAGE.这个对我有用.


Ano*_*lid 5

如果您尝试在 android 10 中尝试将此添加到您的应用程序清单中, android:requestLegacyExternalStorage="true"这可能是 android 10 的权限问题,因为它不允许直接访问文件