bufferedImage.getRGB(x, y) does not yield alpha

Rapti picture Rapti · May 23, 2012 · Viewed 16.2k times · Source

I've got a BufferedImage i and I'd like to get the Color from a certain pixel of that image including the alpha value. The pixel is identified using x and y coordinates.

Here's what I tried:

Color c = new Color(i.getRGB(x, y));

For some reason, the new color object contains the correct RGB but the alpha gets lost.

What am I doing wrong?

Thanks in advance

Answer

matts picture matts · May 23, 2012

The single-parameter Color constructor you're using discards alpha information. Use the two-parameter version instead and pass in true for hasalpha:

Color c = new Color(i.getRGB(x, y), true);

The relevant Javadoc:

Color(int rgb)

Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.

Color(int rgba, boolean hasalpha)

Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.