Android : How to Avoid inconsistent OutOfMemory Exceptions with BitmapFactory.decodeByteArray?

on Thursday, December 4, 2014


I have the following code for my android App:



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;
}
}
};


Sometimes I get users complaining of out of memory exceptions being thrown to their phone. I never run into this problem with my devices, could this be related to their phones having insufficient memory?


Can someone look at this code and give me tips on how to make it more efficient? Thanks!


0 comments:

Post a Comment