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