Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read pixel color in a java BufferedImage with transparency

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

like image 248
Richard H Avatar asked Oct 21 '09 10:10

Richard H


People also ask

How do you color a pixel in Java?

Create a Color object bypassing the new RGB values as parameters. Get the pixel value from the color object using the getRGB() method of the Color class. Set the new pixel value to the image by passing the x and y positions along with the new pixel value to the setRGB() method.

What is the difference between image and BufferedImage in Java?

If you are familiar with Java's util. List, the difference between Image and BufferedImage is the same as the difference between List and LinkedList. Image is a generic concept and BufferedImage is the concrete implementation of the generic concept; kind of like BMW is a make of a Car.

What is the use of BufferedImage?

Java BufferedImage class is a subclass of Image class. It is used to handle and manipulate the image data. A BufferedImage is made of ColorModel of image data. All BufferedImage objects have an upper left corner coordinate of (0, 0).


1 Answers

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

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

like image 92
jarnbjo Avatar answered Oct 19 '22 23:10

jarnbjo