Raiccio
Raiccio

Reputation: 273

Get RGB components from ColorModel

I want to extract the R,G and B values of the pixels of an image. I do it in two ways.

File img_file = new File("../foo.png");
BufferedImage img = ImageIO.read(img_file);

1st method(which works fine):

img.getRaster().getPixel(i, j, rgb);

2nd method(which throws new IllegalArgumentException("More than one component per pixel"))

red = img.getColorModel().getRed(img.getRGB(i, j));

What is the reason for this behaviour?

Upvotes: 0

Views: 2983

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347194

Based on the JavaDocs

An IllegalArgumentException is thrown if pixel values for this ColorModel are not conveniently representable as a single int

It would suggest that the underlying color model is representable by a single int value

You may also want to take a look at this answer for some more details

Typically, you would simply take the int packed pixel from the image and use Color to generate a Color representation and then extract the values from there...

First, get the int packed value of the pixel at x/y...

int pixel = img.getRGB(i, j);

Use this to construct a Color object...

Color color = new Color(pixel, true); // True if you care about the alpha value...

Extract the R, G, B values...

int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();

Now you could simply do some bit maths, but this is simpler and is more readable - IMHO

Upvotes: 0

Jason
Jason

Reputation: 13964

Normally when I want to extract RGB from a BufferedImage I do something like this:

File img_file = new File("../foo.png");
BufferedImage img = ImageIO.read(img_file);

Color color = new Color(img.getRGB(i,j));
int red = color.getRed();

Upvotes: 1

Related Questions