How to read pixel color in a java BufferedImage with transparency

Richard H picture Richard H · Oct 21, 2009 · Viewed 20.6k times · Source

I am reading pixel color in a BufferedImage as follows:

.....
InputStream is = new BufferedInputStream(conn.getInputStream());
BufferedImage image = ImageIO.read(is);

int color = image.getRGB(x, y);

int  red = (colour & 0x00ff0000) >> 16;
int  green = (colour & 0x0000ff00) >> 8;
int  blue = colour & 0x000000ff;

Now this works fine except for png's with transparency. I find that if x,y refer to a transparent pixel with no color, i still read a color, generally the same color as used elsewhere in the image.

How do I detect that the pixel is actually transparent and not colored?

Thanks

Answer

jarnbjo picture jarnbjo · Oct 21, 2009
int alpha = (colour>>24) & 0xff;

The result is also a value ranging from 0 (completely transparent) to 255 (completely opaque).