How can I resolve OutofMemoryError error? (After Bitmap.createScaledBitmap)

180 Views Asked by At

I know, there are a lot of similar questions in Stackoverflow. But I could not solve my problem.

I have some kind of jigsaw puzzle. The pictures in the Drawable-nodpi folder are 2500x1250.

I am trying to resize the images with the following code suggested:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;


        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

I call it like this: (I call these codes several times.)

private Bitmap resizeImg (int rsm) {

    Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght);

   return bmp;
}

I need to use Matrix as the scaling of Imageview. But it's not the size I want. It works right without the Matrix.

I'm solving the Matrix problem like this:

Bitmap.createScaledBitmap

private Bitmap resizeImg (int rsm) {

    Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght);

   //  return bmp;

    Bitmap resized = Bitmap.createScaledBitmap(bmp, wdth,hght,true); //I get OutOfMemoryError this line.
    return resized;

}

This insertion really solves my problem. But every day I get lots of OutOfMemoryError errors.

What do I need to do to fix this error? Please help me. Thank you.

1

There are 1 best solutions below

3
On

1] Add largeHeap as true in android manifest to your application tag:

          android:largeHeap="true"

2] Recycle your all used bitmaps,

    Example:
         bmp.recycle();
         resized.recycle();