A faster way to redraw bitmaps in android?… here is a solution to the problem.
A faster way to redraw bitmaps in android?
I’m working on an image for OCR and I need to change the color of a bunch of pixels in a bitmap. Is there a faster way than setPixel and getPixel? Currently I’m just doing a for loop with a method that checks the input against a bunch of RGB values and returns true if it matches. Thank you very much!
Bitmap img = myImage.copy(Bitmap.Config.ARGB_8888, true);;
for (int w = 0; w < img.getWidth(); w++) {
for (int h = 0; h < img.getHeight(); h++) {
int value = img.getPixel(w, h);
if (filter(value)) {
img.setPixel(w, h, Color.rgb(0, 0, 0));
} else img.setPixel(w, h, Color.rgb(255, 255, 255));
}
}
Solution
Just wanted to follow up and post the code to see if anyone found it through a search.
My code in the issue took an average of 3.4 seconds, and the suggested code below using Gabe took less than 200 milliseconds. I also added a length variable because I read that not calling array.length() improves performance with every iteration, but doesn’t seem to do much good in testing
int width = img.getWidth();
int height = img.getHeight();
int length = width * height;
int[] pixels = new int[width*height];
img.getPixels(pixels, 0, width, 0, 0, width, height);
for (int i = 0; i < length; i++) {
if (filter(pixels[i])) {
pixels[i] = Color.rgb(0, 0, 0);
} else pixels[i] = Color.rgb(255, 255, 255);
}
img.setPixels(pixels, 0, width, 0, 0, width, height);