0

I have a code which takes a bitmap and converts the X and Y coordinate to RGB:

int pixel = bitmap.getPixel((int)x,(int) y);
inRed = Color.red(pixel);
inBlue = Color.blue(pixel);
inGreen = Color.green(pixel);

How do I convert a given RGB and get the X and Y coordinate within the bitmap?

Si8
  • 9,141
  • 22
  • 109
  • 221

1 Answers1

1

To find the first pixel in a Bitmap with given Color:

int color = // your color
int x, y; // used for output
boolean found = false;
for (int ix = 0; ix < bitmap.getWidth(); ++ix) {
  for (int iy = 0; iy < bitmap.getHeight(); ++iy) {
    if (color == bitmap.getPixel(ix, iy) {
      found = true;
      x = ix;
      y = iy;
      break;
    }
  }
}
flx
  • 14,146
  • 11
  • 55
  • 70
  • Thanks for the post... the color has to be in what form? What has to be in the `color=?` – Si8 Feb 11 '14 at 04:04
  • Basically it's 0xAARRGGBB. You can create it with `Color.argb()` or `Color.rgb()`. – flx Feb 11 '14 at 04:07
  • No, this will find the *last* pixel with the given color. You need to add a `break` inside the `for-loop` for this to find the *first* pixel. – Phil Feb 11 '14 at 04:35
  • sure. forgot that. added it to the answer. – flx Feb 11 '14 at 04:36
  • What is the difference between first and last pixel? just wondering :/ – Si8 Feb 11 '14 at 13:34
  • Well, you might have more than one pixel with the same color, right? This implementation starts in the upper left corner and scans line by line for the first pixel with the given color. – flx Feb 11 '14 at 14:45
  • The question remail is I am using an image for a thumb kind of like a cross hair. What if the pixel is toward the edge and it force the thumb to go out of the layout view. Is there any way to avoid that? Like find another location with the same pixel? Btw that's a nice solution. – Si8 Feb 11 '14 at 16:20
  • I don't get it. Sorry. – flx Feb 11 '14 at 16:54
  • I will explain to you.. I was vague in my previous post. – Si8 Feb 11 '14 at 18:15