Basic image creation in Java: BufferedImage
In this section, we will look at basic (graphic) image creation in Java. Specifically, we will look
at how to perform the following image operations in Java:
- create a blank image in memory;
- set pixels on the image to particular colours;
- save the image in a common format such as PNG or JPEG.
How to create an image (in memory) in Java
A graphic image in memory in Java is most conveniently represented by a BufferedImage1.
This class represents an image that you can conveniently modify and save in one of the standard image
formats.
To create a BufferedImage, we must specify the image's dimensions in pixels. We must also
specify the format of the image: in other words, the range of colours that each pixel can
represent, and how they are represented. The BufferedImage class contains various constants
offering different types which we will look at later.
However, as a general rule of thumb:
- if you require your image to support transparency (also called alpha), then use
BufferedImage.TYPE_INT_ARGB;
- otherwise, use BufferedImage.TYPE_INT_RGB.
(See also our comparison of BufferedImage performance with these different image types.)
So for example, to create a 256x256 pixel image without support for transparency, do the following:
import java.awt.image.BufferedImage;
...
BufferedImage img = new BufferedImage(256, 256,
BufferedImage.TYPE_INT_RGB);
Now we are ready to set pixels on img and eventually save it to disk in a
standard image format such as PNG.
There are generally two ways to set pixels on a graphic image in Java
represented by a BufferedImage:
- a low-level method: we can set pixels directly on the BufferedImage
by one of its setRGB() methods;
- a high-level method:: we can obtain a graphics context to draw on
to the surface of the imge by specifying what we want to draw more 'logically'
in terms of geometric shapes, other images etc, without worrying about the details
of what specific pixels correspond to, say, a circle or polygon.
Which approach is more appropriate obviously depends on whether we want to manipulate
pixels at a very "raw" level.
Next: setting individual pixels
On the next page, we look at how to set individual
pixels on a BufferedImage with setRGB().
Later on, we will also look at how to save
a BufferedImage as a PNG or JPEG etc. This effectively allows you to create image
files such as PNGs and JPEGs within in code in Java.
1. Historically, in image was created or loaded in Java via one of the
Toolkit.createImage() methods. With the possible exception of some cases of loading an image from
a URL inside an Applet for display purposes, the Toolkit.createImage() methods are inflexible,
cumbersome and rarely behave as you want them to and I recommend that you simply avoid them.