Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BufferedImage getRGB method and Color class

What do the x and y parameters in the getRGB(x, y) method represent? What does the numerical return value represent?

How do I identify the color of specific pixels within a BufferedImage that is displayed on a DrawingPanel? Ideally I'd like to 'find' a word within an image, and underline or outline this word to create a relevant hyperlink. How can I translate these numerical values into human understandable colors like 'red' 'green' or 'blue'?

Yes, I understand that in the Color class an alpha value of 0-255 represents transparent to opaque. But what does this imply for the actual color? I'm happy to clarify if this doesn't make sense. Thank you for reading.

like image 882
Agent Pants Avatar asked Nov 22 '12 17:11

Agent Pants


People also ask

What is getRGB Java?

getRGB(int x, int y) Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace.

How do I change the pixel color 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 use of BufferedImage in Java?

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).

What is the difference between BufferedImage and image?

A BufferedImage is essentially an Image with an accessible data buffer. It is therefore more efficient to work directly with BufferedImage. A BufferedImage has a ColorModel and a Raster of image data. The ColorModel provides a color interpretation of the image's pixel data.


1 Answers

The x and y coordinates represent the pixel location, x going from left to right and y going from top to bottom (both starting at 0). So (0, 0) is the upper left pixel, and (width-1, height-1) is the bottom right pixel.

The integer value returned has the R, G, B and (potentially) Alpha values packed into a single int. Remember that an int contains 32 bits, so 8 of those bits are allocated to each of the values.

But, if you're not to good with shifting bits around inside an integer, the easiest thing to do is pass the integer value to the constructor of Color:

int rgba = image.getRGB(coordinates);
Color col = new Color(rgba, true);
int r = col.getRed();
int g = col.getGreen();
...

Obviously, recognising where a word is from raw pixel values is a whole nother, quite complex, problem.

like image 174
Neil Coffey Avatar answered Sep 28 '22 12:09

Neil Coffey