Setting individual pixels on a BufferedImage

In the previous section, we saw how to create an image in Java represented by a BufferedImage object. In this section, we look at how to manipulate an image in Java at a fairly low or "raw" level by setting the colour of individual pixels on a BufferedImage.

Setting an individual pixel based on red, green, blue values

As you are probably aware, colours are usually expressed in terms of a combination of red, green and blue values. Given each of these expressed as an integer between 0 and 255 (i.e. a single unsigned byte), you can set an individual pixel of a BufferedImage to that colour as follows:

int r = // red component 0...255
int g = // green component 0...255
int b = // blue component 0...255
int col = (r << 16) | (g << 8) | b;
img.setRGB(x, y, col);

In other words, the red, green and blue components are merged into a single integer, which is then passed to BufferedImage.setRGB().

Setting an pixel with reg, green, blue and transparency (alpha) values

If you need to manipulate a BufferedImage that supports transparency, then you need to remember the following:

int r = // red component 0...255
int g = // green component 0...255
int b = // blue component 0...255
int a = // alpha (transparency) component 0...255
int col = (a << 24) | (r << 16) | (g << 8) | b;
img.setRGB(x, y, col);

From this point of view, the setRGB() method is slightly badly named, because the integer value it takes actually incorporates red, green, blue and alpha.

Setting the pixel from a Color object

If you have a Color object representing the colour that you wish to set (either one of the Color constants such as Color.red or a Color that you have created), then you can call the Color object's getRGB() method to retrun an appropriate integer. The following sets the top-left pixel of the image to red:

Color colour = Color.red();
img.setRGB(colour.getRGB());

Notice that, like BufferedImage.setRGB(), the Color.getRGB() method is a slight misnomer because it actually returns the alpha value of the colour along with the red, green and blue components. But that's OK because it's what BufferedImage.setRGB() is expecting!

Next: writing a BufferedImage to file

A common requirement is to write an image to a standard file such as a PNG file or JPEG. Luckily this is straightforward in Java. On the next page, we look at how to write a BufferedImage to file using one of these standard formats.