我的 Android 应用程序有以下代码:
private PictureCallback pictureTakenCallback = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bmp = null;
Bitmap scaledBitmap = null;
ByteArrayOutputStream baos = null;
showLoading(true);//UI crap
try
{
bmp = BitmapFactory.decodeByteArray(data, 0, data.length); //OOM Exception Thrown Here
//if the bitmap is smaller than 1600 wide, scale it up while preserving aspect ratio
if(bmp.getWidth() < 1600) {
int originalHeight = bmp.getHeight();
int originalWidth = bmp.getWidth();
scaledBitmap = Bitmap.createScaledBitmap(bmp, 1600,
originalHeight*1600/originalWidth, true);
bmp = scaledBitmap;
scaledBitmap = null;
}
baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 30, baos); // 30% compression
image = baos.toByteArray();
submitImage();
}
catch (java.lang.OutOfMemoryError e) {
e.printStackTrace();
showLoading(false);
}
catch (Exception e) {
e.printStackTrace();
showLoading(false);
}
finally
{
bmp = null;
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
baos = null;
}
}
};
有时,我会收到用户提示手机内存不足的异常。我的设备从未遇到过这个问题,这可能与他们的手机内存不足有关吗?
有人可以看看这段代码并给我一些如何提高效率的提示吗? 谢谢!
最佳答案
始终尝试在 Manifest 中像这样 android:largeHeap="true"
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
>
关于java - 如何避免 BitmapFactory.decodeByteArray 出现不一致的 OutOfMemory 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27308541/