Reputation: 11
I go through a bitmap in android and i want to get a the color of each pixel and count it if it has a certain value i.e if it is brown.
I use the following code. The code works but it is extremely slow due to the big number of pixels in the image, which of course I need for correct results.
for(int i = 1; i <= 100; i++){
for(int j = 1; j <= 100; j++) {
int pixel = bitmap.getPixel(i,j);
R1 = Color.red(pixel);
G1 = Color.green(pixel);
B1 = Color.blue(pixel);
if((R1 == 155) && (G1 == 155) && (B1 == 155)) {
countthecolor = countthecolor + 1;
}
}
}
Upvotes: 0
Views: 2214
Reputation: 7698
You can try to use getPixels
which returns a large array of length = bitmap.width * bitmap.height
.
Then you can loop through this array and perform your operation. This will be a little faster however, now you will have to manage your memory since you already have the bitmap and now this array in the memory. So I recommend to recycle the bitmap if you don't need it anymore.
int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), x, y, myBitmap.getHeight(), myBitmap.getWidth());
You can further optimize your loop using bitwise operations to get the individual RGB values (note for alpha may or may not be there):
Alpha = (pixel & 0xff000000)
R1 = (pixel >> 16) & 0xff;
G1 = (pixel >> 8) & 0xff;
B1 = (pixel & 0xff);
May want to take a look at this!
Upvotes: 2