Android – how to find xy coordinate of pixel in pixel array from android bitmap

androidbitmappixel-manipulation

i have an int array derived from a bitmap using the Bitmap.getPixels() method. This method populates the array with the pixels from the Bitmap. How can i get the xy coordinate of each pixel when i loop through that array? thanks in advance Mat.

[update]
Thanks for the math. i've tried the following code. i've a bitmap where i've changed the first 50000 pixels to white. i now want to iterate through the bitmap and change all the white pixels to red. atm there is just one red line through the block of white pixels at the top of the bitmap. have you any ideas? thanks alot.

int length = bgr.getWidth()*bgr.getHeight();
                    int[] pixels = new int[length];
                    bgr.getPixels(pixels,0,bgr.getWidth(),0,0,bgr.getWidth(),bgr.getHeight());
                    for (int i=0;i<50000;i++){
                    // If the bitmap is in ARGB_8888 format

                        pixels[i] = Color.WHITE;//0xffffffff;

                      }

                    bgr.setPixels(pixels,0,bgr.getWidth(),0,0,bgr.getWidth(),bgr.getHeight());




                        int t = 0;
                    int y  = t / bgr.getWidth();
                    int x = t - (y * bgr.getWidth());

                  for( t = 0; t < length; t++){

                      int pixel = bgr.getPixel(x,y);

                      if(pixel == Color.WHITE){

                          bgr.setPixel(x,y,Color.RED);
                          x++;y++;
                      }
                  }

Best Answer

Here's a code example, which possibly does what you're describing. As I understood your goal at least;

int length = bgr.getWidth()*bgr.getHeight();
int[] pixels = new int[length];

bgr.getPixels(pixels,0,bgr.getWidth(),0,0,bgr.getWidth(),bgr.getHeight());

// Change first 50000 pixels to white. You most definitely wanted
// to check i < length too, but leaving it as-is.
for (int i=0;i<50000;i++){
    pixels[i] = Color.WHITE;
}

// I'm a bit confused why this is here as you have pixels[] to do
// modification on. And it would be a bit more efficient way to do all of
// these changes on pixels array before setting them back to bgr.
// But taken this is an experiment with Bitmaps (or homework, hopefully not ;)
// rather good idea actually.
bgr.setPixels(pixels, 0, bgr.getWidth(), 0, 0, bgr.getWidth(), bgr.getHeight());

for (int i=0; i < length; ++i) {
    int y = i / bgr.getWidth();
    int x = i - (y * bgr.getWidth());
    int pixel = bgr.getPixel(x, y);
    if(pixel == Color.WHITE){
        bgr.setPixel(x ,y , Color.RED);
    }
}