Vinod
Vinod

Reputation: 32891

Is there a faster way to process arrays in java android?

I have a bitmap which i am loading each pixel to array. Later i run through each array pixel data and check if the color is RED and change it to BLACK. So if it is a 1024x1024 image, i have to go through a array of 1048576 length. Is there any faster way to process this. Any kind of advice to improve performance is welcome. I basically need to check for a color in image and change it. Below is my code sample.

int[] allpixels = new int[myBitmap.getHeight() * myBitmap.getWidth()];

myBitmap.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0,
                   myBitmap.getWidth(), myBitmap.getHeight());

for (int i = 0; i < myBitmap.getHeight() * myBitmap.getWidth(); i++) {
    if (allpixels[i] == fromColor) {
        allpixels[i] = toColor;
    }
}
Bitmap bitmapCopy = myBitmap.copy(myBitmap.getConfig(), true); 
bitmapCopy.setPixels(allpixels, 0, myBitmap.getWidth(), 0, 0,
                     myBitmap.getWidth(), myBitmap.getHeight());

Upvotes: 2

Views: 244

Answers (1)

kabuko
kabuko

Reputation: 36302

In your for loop's comparison statement you're getting the height and width and multiplying every time. You can cache that. That should get you a bit of performance boost probably, but otherwise it's just plain a lot of work that your algorithm requires. There's not a ton you can do about it. As suggested in the comment above, you could multithread it, but there's no guarantee that you have multiple cores/processors. If performance is that critical, you could consider using RenderScript to do it if you can require ICS. See this post on image processing for more details.

Actually another approach you might try is to use setColorFilter. Might need two applications to get a mask with original color then reapply the mask with the new color.

Upvotes: 1

Related Questions