It was almost four years ago that I wrote my first column for ComputerWorld Canada, demonstrating how a Java servlet could display dynamic images using a database as its source. The recent work of a colleague has me feeling nostalgic, so Jarrod LeDrew and I have teamed up to revisit this topic — with a twist.

We will use Java to create the image on-the-fly. Jarrod has already put this technology to use in a cool reporting application. The example code requires the JAI (Java Advanced Imaging) packages.

Line 9 creates a BufferedImage, which you can think of as the canvas that we’ll draw on. Our canvas is 300 pixels wide by 300 pixels tall. By default, this will display as a 300×300 black square when rendered for display in a browser. The third argument in the constructor specifies the image type. A variety of image types are available as constants in the BufferedImage class. We will use 8-bit RGB.

The Graphics object we get on Line 10 is responsible for all of the drawing operations. We set the colour to white, draw a square and add some text. The setColor method changes the active “pen” colour — we could set it to blue, for example, and continue drawing without altering what we already created in white.

Most of the drawing operations have integer arguments to specify position and size in pixels.

Lines 14 and 15 are the critical bit — where our canvas (BufferedImage) gets encoded to the JPEG format using JAI. This is now a regular image that we can write to the servlet’s output stream. Line 18 lets the browser know that an image is coming back from the servlet, and Line 19 specifies that it should be opened “inline” (within the browser) as opposed to prompting the user to download it as a file. Line 19 also specifies a default filename.

Happy square drawing!

1: import javax.servlet.*;

2: import javax.servlet.http.*;

3: import*;

4: import java.awt.image.*;

5: import java.awt.*;

6: import com.sun.image.codec.jpeg.*;

7: public class ImageCreate extends HttpServlet {

8: public void doGet(HttpServletRequest request,

HttpServletResponse response) throws IOException,

ServletException {

9: BufferedImage bi = new BufferedImage(300,300,BufferedImage.TYPE_INT_RGB);

10: Graphics g = bi.createGraphics();

11: g.setColor(Color.WHITE);

12: g.drawRect(10,10,200,200);

13: g.drawString(“This is my square!”,10,250);

14: JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(new ByteArrayOutputStream());

15: en.encode(bi);

16: ByteArrayOutputStream os =

(ByteArrayOutputStream) en.getOutputStream();

17: byte[] ba = os.toByteArray();

18: response.setContentType(“image/jpeg”);

19: response.setHeader(“Content-Disposition”,

“inline; filename=MyImage.jpg”);

20: response.setContentLength(ba.length);

21: ServletOutputStream out = response.getOutputStream();

22: out.write(ba, 0, ba.length);

23: out.flush();

24: }

25: }

Cooney is a managing partner and chief software architect for Rivervine Technologies Inc. Contact him at