Search code examples
androidfilebitmapout-of-memoryscale

Android Getting scaled image file length



Here is my problem:
I'm asking my user to choose between different sizes of a same image in order to upload it.
My interface shows 4 buttons with each giving informations about the width, the height of the image, and the length of the file.

I managed to produce the four versions of the image calling Bitmap.createScaledBitmap, then compressing those bitmaps to files again.
I'm well aware I need to recycle the bitmap and delete the files when I'm done.

However, when trying to compute a big file, the method createScaledBitmap throws an out of memory exception. I was told to use the option inJustDecodeBounds to decode the file but it would return a null bitmap.

Does someone have an idea on how to solve this problem?

Here is the code:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bmp = getScaledBitmap(BitmapFactory.decodeFile(uri, options), ratio);

private Bitmap getScaledBitmap(Bitmap bmp, float ratio) {
    int srcWidth = bmp.getWidth();
    int srcHeight = bmp.getHeight();
    int dstWidth = (int)(srcWidth * ratio);
    int dstHeight = (int)(srcHeight * ratio);
    Bitmap result = Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true);
    bmp.recycle();
    return result;
}

Solution

  • To answer your replies, I don't consider it to be a duplicate. I previously found the thread you linked but it's quite old and it didn't solve my problem.

    Anyway, I solved the problem.

    I first tried using Glide library which is said to be better for memory management. Though, there was an improvement but it wasn't perfect and the problem occured again.

    Using android:largeHeap="true" put an end to my nightmare. This has to be set in the application field of your manifest.

    I hope this will help someone else.