Search code examples
androidcolorsbitmappixel

How to efficiently get and set bitmap pixels


I am currently making an app that involves altering the RGB values of pixels in a bitmap and creating a new bitmap after.

My problem is I need help increasing speed of this process. (It can take minutes to process a bitmap with inSampleSize = 2 and forever to process an inSampleSize = 1) Right now, I am using the getPixel and setPixel methods to alter the pixels and believe these two methods are the root of the problem as they are very inefficient. The getPixels method isn't suitable as I am not altering each pixel in order (ex. getting a pixel and changing a radius of 5 pixels around it to the same colour) unless anyone knows of a way to use getPixels (perhaps be able to put the pixels in a 2D array).

This is part of my code:

public static final alteredBitmp(Bitmap bp)
{


 //initialize variables
 // ..................


  Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);

    for (int x = 0; x < width; x++) {
        int left = Math.max(0, x - RADIUS);
        int right = Math.min(x + RADIUS, width - 1);
        for (int y = 0; y < height; ++y) {

            int top = Math.max(0, y - RADIUS);
            int bottom = Math.min(y + RADIUS, height - 1);

            int maxIndex = -1;

            for (int j = top; j <= bottom; j++) {
                for (int i = left; i <= right; i++) {

                    pixelColor = bitmap.getPixel(i, j);

                    //get rgb values
                    //make changes to those values
                }
            }
        }
     }

     //set new rgb values


     bitmap.setPixel(x, y, Color.rgb(r, g, b));

     //return new bitmap

Much thanks in advance!


Solution

  • Consider looking at RenderScript, which is Android's high performance compute framework. As you are iterating over width x height number of pixels and altering each one which in a modern device could be around a million pixels or higher, doing it in a single thread can take minutes. RenderScript can parallelize operations over CPU or the GPU where possible.

    http://android-developers.blogspot.com/2012/01/levels-in-renderscript.html

    http://developer.android.com/guide/topics/renderscript/index.html

    Google IO 2013 session: https://youtu.be/uzBw6AWCBpU

    RenderScript compatibility library: http://android-developers.blogspot.com/2013/09/renderscript-in-android-support-library.html