11

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

Topera
  • 12,223
  • 15
  • 67
  • 104
Richard H
  • 38,037
  • 37
  • 111
  • 138

1 Answers1

17
int alpha = (colour>>24) & 0xff;

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

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • Keep in mind that if alpha is 0 (transparent) then the color values don't really matter. Probably an optimization step in some editors to not bother setting color values when alpha is 0. – basszero Oct 21 '09 at 10:41
  • 1
    thanks - I'm surprised the BufferedImage class doesn't have a method "int getTransparency(int x, int y);" – greenimpala Jun 22 '11 at 15:25
  • Does every picture contain transparency value? – Jürgen K. Nov 05 '15 at 15:23
  • 1
    @JürgenK. After being loaded by the Java API, yes, every image should have a transparency value. If the image was loaded from a file format not supporting transparency (e.g. JPEG), the transparency value for every pixel will be set to 0xff (100% opaque). – jarnbjo Nov 05 '15 at 16:53
  • Thanks for your answer. I had the hope to calculate somekind of haziness in pictures with fog, using transparency. Wrong choice, i guess – Jürgen K. Nov 05 '15 at 17:03