I have a method to resize bitmap decoded from a file path or create s thumbnail by using ThumbnailUtils. then to set the bitmap as a background for a custom view or draw on canvas.
in few cases it cause OutOfMemoryError
java.lang.OutOfMemoryError:
at dalvik.system.VMRuntime.newNonMovableArray (VMRuntime.java)
at android.graphics.Bitmap.nativeCreate (Bitmap.java)
at android.graphics.Bitmap.createBitmap (Bitmap.java:942)
at android.graphics.Bitmap.createBitmap (Bitmap.java:913)
at android.graphics.Bitmap.createBitmap (Bitmap.java:844)
at android.media.ThumbnailUtils.transform (ThumbnailUtils.java:425)
at android.media.ThumbnailUtils.extractThumbnail (ThumbnailUtils.java:228)
at android.media.ThumbnailUtils.extractThumbnail (ThumbnailUtils.java:203)
mostly caused by ThumbnailUtils maybe because I'm not scaling down the bitmap before extracting thumbnail?
how to do this without loading more on memory and in general how this methods can be more optimized
// w = view Width, h = view Height
public BitmapDrawable decodeBitmap(int w, int h) {
Bitmap bitmap = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
bitmap = BitmapFactory.decodeFile(BackgroundImage,options);
if(scaleType==0) { //center crop
bitmap = cropCenter(bitmap,w,h);
}else if(scaleType==1) { //fitxy
bitmap = resize(bitmap,w,h);
}
return new BitmapDrawable(mContext.getResources(), bitmap);
} catch (Exception e) {
}
return null;
}
private Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
try{
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioMax > ratioBitmap) {
finalWidth = (int) ((float) maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float) maxWidth / ratioBitmap);
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, false);
return image;
}
} catch (Exception e) {
}
return image;
}
private Bitmap cropCenter(Bitmap bmp, int maxWidth, int maxHeight) {
try{
return ThumbnailUtils.extractThumbnail(bmp, maxWidth, maxHeight);
} catch (Exception e) {
}
return bmp;
}
I'm using BitmapDrawable to use setBackground(Drawable);