7

Ok so I'm working on a program that takes in an image, isolates a block of pixels into an array, and then gets each individual rgb value for each pixel in that array.

When I do this

//first pic of image
//just a test
int pix = myImage.getRGB(0,0)
System.out.println(pix);

It spits out -16106634

I need to get the (R, G, B) value out of this int value

Is there a formula, alg, method?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
shoconinja
  • 195
  • 1
  • 3
  • 11

2 Answers2

12

The BufferedImage.getRGB(int x, int y) method always returns a pixel in the TYPE_INT_ARGB color model. So you just need to isolate the right bits for each color, like this:

int pix = myImage.getRGB(0, 0);
int r = (pix >> 16) & 0xFF;
int g = (pix >> 8) & 0xFF;
int b = pix & 0xFF;

If you happen to want the alpha component:

int a = (pix >> 24) & 0xFF;

Alternatively you can use the Color(int rgba, boolean hasalpha) constructor for convenience (at the cost of performance).

WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • Cool. Make sure you copied the bit shifts in the right direction... I actually made a typo the first time and fixed it in an edit. – WhiteFang34 Apr 03 '11 at 00:14
2
int pix = myImage.getRGB(0,0);
Color c = new Color(pix,true); // true for hasalpha
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
Bala R
  • 107,317
  • 23
  • 199
  • 210