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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With