我正在使用 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.nativeDecodeStream
、BitmapFactory.finishDecode
等)。问题可能出在这些方法之一上,所以如果我是你,我会尝试阅读并理解它们是如何工作的,以便我知道在哪些情况下它们返回 null。
关于java - Android 将相机图像加载为位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2947253/