我有我的Android應用程序下面的代碼:如何避免與BitmapFactory.decodeByteArray不一致的OutOfMemory異常?
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;
}
}
};
有時候我的用戶報怨內存不足異常的拋出自己的手機。我從未遇到過使用我的設備的問題,這可能與其內存不足的手機有關嗎?
有人可以看看這段代碼,並給我提示如何使它更有效嗎? 謝謝!
試試這個http://voidcanvas.com/whatsapp-like-image-compression-in-android/ – 2014-12-05 04:04:17