Lisa Anne
Lisa Anne

Reputation: 4595

Android: modify and save Bitmap, how to avoid OOM?

In my project I need to manipulate a Bitmap and save it.

To manipulate the image I apply a matrix, like this:

Bitmap b = Bitmap.createBitmap(((BitmapDrawable) imageView.getDrawable()).getBitmap(), 0, 0,width, height, matrix, true);

And I save it like this:

b.compress(Bitmap.CompressFormat.JPEG, 100, out);

The problem is that if do that I can get an OOM error if the bitmap is large.

Any suggestion of how to avoid it?

Unfortunately scaling down the Bitmap is not an acceptable solution, because I need to preserve the bitmap quality.

Upvotes: 1

Views: 426

Answers (1)

patloew
patloew

Reputation: 1090

I also had quite some OOMs with Bitmaps, especially on older (Samsung) devices. A simple approach you can use is to catch the OOM, initiate the GC and then try again. If it fails again, you can (for example) show an error message to the user.

private void compressBitmap(/* args */) {
    Bitmap b = Bitmap.createBitmap(((BitmapDrawable) imageView.getDrawable()).getBitmap(), 0, 0,width, height, matrix, true);
    b.compress(Bitmap.CompressFormat.JPEG, 100, out);
}

try {
    compressBitmap(/* args */);
} catch(OutOfMemoryError e) {
    System.gc();
    // try again
    try {
        compressBitmap(/* args */);
    } catch(OutOfMemoryError e) {
        System.gc();
        // Inform user about the error. It's better than the app crashing
    }
}

This is however only a workaround. If you really want to effectively prevent OOMs in this situation, I think you have to use the NDK. In any case, it’s better than the app crashing.

Upvotes: 1

Related Questions