0

I'm having the OutOfMemory error when inverting a bitmap.. Here is the code I use to invert:

public Bitmap invertBitmap(Bitmap bm) {
        Bitmap src = bm.copy(bm.getConfig(), true);

        // image size
        int height = src.getHeight();
        int width = src.getWidth();
        int length = height * width;
        int[] array = new int[length];
        src.getPixels(array, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());
        int A, R, G, B;
        for (int i = 0; i < array.length; i++) {
            A = Color.alpha(array[i]);

            R = 255 - Color.red(array[i]);
            G = 255 - Color.green(array[i]);
            B = 255 - Color.blue(array[i]);

            array[i] = Color.argb(A, R, G, B);
        }
        src.setPixels(array, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());

        return src;
    }

The image is ~80 kb big, the dimensions are 800x1294 and the picture has words which are black and an invisible background..
The images are in a ViewPager..

Omar
  • 7,835
  • 14
  • 62
  • 108

3 Answers3

0

when you copy bm, try: bm = null;

Jamshid
  • 340
  • 3
  • 12
0

In android , due to 16MB (on almost all phones) memory cap for applications, it is not wise to hold entire bitmap in memory. This is a common scenario and is happening to may developers.

You can get many information about this problem in this stackoverflow thread. But I really urges you to read android's official document about efficient usage of Bitmaps. They are here and here.

Community
  • 1
  • 1
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
0

The memory size used by an image in completelly different from the file size of that image.

While in a file the image may be compressed using different alghorithms (jpg, png, etc.) and when loaded in memory as a bitmap, it uses 2 or 4 bytes per pixel.

So in your case (you are not sowing the code but it lloks like you are using 4 bytes per pixel), the memory size per image is:

size = width * height * 4; // this is aprox 2MB

In your code, first you copy the original bitmap to a new one, and then ceate an array to manipulate the colors. So in total you are using size x 3 = 6MB per image inversion.

There are plenty of examples on how to handle large bitmap in Android, but I'll leave you what I think is the most important topics:

  • Try to use only one copy of bitmap in your code above
  • If you are only having words in your image use Bitmap.Config = RGB_565. This only uses 2 bytes per pixel, reducing size by half.
  • Call recycle() on a bitmap that you don't need anymore.
  • Have a lool at scale option in Bitmap.Factory. You may reduce the size of image that still fit your needs.

good luck.

Luis
  • 11,978
  • 3
  • 27
  • 35