2

I need to iterate through each pixel of the Bitmap image, this is my code, but it's too slow

    Bitmap img=......;
    int imgWidth = img.getWidth();
    int imgHeight = img.getHeight();
    for (int i = 0; i < imgWidth; i++) {
        for (int j = 0; j < imgHeight; j++) {
            int color = img.getPixel(i, j);
            int R = android.graphics.Color.red(color);
            int G = android.graphics.Color.green(color);
            int B = android.graphics.Color.blue(color);
            // do something
        }
    }
Hermes
  • 2,828
  • 2
  • 14
  • 34
Jinnrry
  • 405
  • 1
  • 5
  • 18

1 Answers1

1

I had solved this problem.This is my new code.

    int[] colors = new int[img.getWidth() * img.getHeight()];
    img.getPixels(colors, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
    for (int i = 0; i < colors.length; i++) {
            int y = (int) (i / img.getWidth());
            int x = i % img.getWidth();
            int R = android.graphics.Color.red(colors[i]);
            int G = android.graphics.Color.green(colors[i]);
            int B = android.graphics.Color.blue(colors[i]);
        }
    }

The new solution takes about 8 seconds, and the old solution takes 27 seconds.

Jinnrry
  • 405
  • 1
  • 5
  • 18
  • 8 seconds is still a long time to traverse an image. Sadly I don’t know anything about Java to help you with this. – Cris Luengo Jun 22 '19 at 19:06