How to read pixel color in a java BufferedImage with transparency

20,835
int alpha = (colour>>24) & 0xff;

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

Share:
20,835
Richard H
Author by

Richard H

Updated on October 20, 2020

Comments

  • Richard H
    Richard H over 3 years

    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

  • Anne Porosoff
    Anne Porosoff over 14 years
    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.
  • greenimpala
    greenimpala almost 13 years
    thanks - I'm surprised the BufferedImage class doesn't have a method "int getTransparency(int x, int y);"
  • Jürgen K.
    Jürgen K. over 8 years
    Does every picture contain transparency value?
  • jarnbjo
    jarnbjo over 8 years
    @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).
  • Jürgen K.
    Jürgen K. over 8 years
    Thanks for your answer. I had the hope to calculate somekind of haziness in pictures with fog, using transparency. Wrong choice, i guess