我正在使用bitmapfactory.decodefile将图像的位图加载到我的应用程序中。但是,该函数在大图像(例如来自相机的图像)上返回空值。文件路径绝对正确,我只是不明白为什么它会返回null。我试过超采样,但似乎没用。
有人知道它为什么会这样做,或者我如何更容易地将相机拍摄的图像加载到位图中吗?
下面是我使用的代码:
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;
}
最佳答案
您需要提供有关您的问题的更多信息,例如您正在使用的代码片段。如果您想知道BitmapFactory.decodeFile
方法何时/为什么返回null,可以直接读取其源代码:http://casidiablo.in/BitmapFactory
例如,导致BitmapFactory.decodeFile
返回null的原因之一是打开文件时是否有问题。奇怪的是,开发人员没有记录任何这样的问题…看看评论“什么都不要做。如果在打开时发生异常,bm将为空。“
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。