java - Android 将相机图像加载为位图

标签 java android bitmap

我正在使用 BitmapFactory.decodeFile 将图像位图加载到我的应用程序中。但是,该函数在大图像(例如来自相机的图像)上返回 null。文件路径绝对是正确的,我只是不明白为什么它会返回空。我尝试过 super 采样,但似乎没有帮助。

有谁知道为什么会这样做或者我如何更轻松地将相机拍摄的图像加载到位图中?

这是我正在使用的代码:

public static Bitmap loadBitmap(String filePath){
    Bitmap result = BitmapFactory.decodeFile(filePath);

    if(result == null){
        if(filePath.contains(".jpg") || filePath.contains(".png")){
            //This is the error that occurs when I attempt to load an image from the Camera DCIM folder or a large png I imported from my computer.
            Utils.Toast("Could not load file -- too big?"); 
        } else {
            Utils.Toast("Could not load file -- image file type is not supported");
        }
    }
    return result;
}

最佳答案

您需要提供有关您的问题的更多信息,例如您正在使用的代码 fragment 。如果你想知道BitmapFactory.decodeFile方法何时/为何返回null,可以直接阅读其源代码:http://casidiablo.in/BitmapFactory

例如,导致 BitmapFactory.decodeFile 返回 null 的原因之一是打开文件时出现问题。奇怪的是,开发人员没有记录任何出现此类问题的内容...查看注释“什么也不做。如果异常发生在打开时,bm 将为 null。”

public static Bitmap decodeFile(String pathName, Options opts) {
    Bitmap bm = null;
    InputStream stream = null;
    try {
        stream = new FileInputStream(pathName);
        bm = decodeStream(stream, null, opts);
    } catch (Exception e) {
        /*  do nothing.
            If the exception happened on open, bm will be null.
        */
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // do nothing here
            }
        }
    }
    return bm;
}

如您所见,BitmapFactory.decodeFile 不能独立工作...但它使用 BitmapFactory 类的一些其他方法(例如, BitmapFactory.decodeStream、BitmapFactory.nativeDecodeStreamBitmapFactory.finishDecode 等)。问题可能出在这些方法之一上,所以如果我是你,我会尝试阅读并理解它们是如何工作的,以便我知道在哪些情况下它们返回 null。

关于java - Android 将相机图像加载为位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2947253/

相关文章:

java - Spring设置抽象bean属性值

java - 如何将字符串转换为 JSON?

java - 如何使用非通用参数调用方法(反射)?

c# - 将图像转换为字节数组的最快方法

android - 修复了 Android 上使用 fmx 字体的 : canvas. 填充文本被 block 背景包围的问题

java - 将数组的内容写入文本文件

java - 如果不为空,则将值放入 map

设置 CursorAdapter 时 Android 应用强制关闭

android - 尝试将 Firebase 与 AndroidX 一起使用会产生错误 : Failed resolution of: Landroid/support/v4/util/ArrayMap;

android - 保存从相机拍摄的图片时,android 中出现 java.lang.OutOfMemoryError