How do I create an image (GIF, JPEG, etc.) on the fly from a servlet?

Alex Chaffee

To create an image or do image processing from Java, there are several packages and classes available. See the Purple Servlet References for a list.

Once you have an image file in your servlet, you have two choices:

  1. Write the file to disk and provide a link to it. Make sure you write it to a location that's in your web server directory tree (not just anywhere on the server's disk). You can use the Java 2 JPEGCodec class, or Acme Labs' GIFEncoder class, to turn a Java Graphics into an image file or bytestream.

    (Note that in some servlet engine setups, the servlet directory is not accessible by the web server, only by the servlet engine, which means you won't be able to access it through an http:// URL.) You can either send an IMG tag in the HTML your servlet is outputting, or send an HTTP redirect to make the browser download the image directly (as its own page).

    (CookieDetector (http://www.purpletech.com/code/CookieDetector.html) has an example, with source code, of sending a redirect.)

    Pro: the image can be cached by the browser, and successive requests don't need to execute the servlet again, reducing server load.

    Con: the image files will never be deleted from your disk, so you'll either have to write a script to periodically clean out the images directory, or go in and delete them by hand. (Or buy a bigger hard disk :-) ).

  2. Output the image directly from the servlet. You do this by setting the Content-type header to image/gif (for GIFs), or image/jpeg (for JPEGs). You then open the HttpResponse output stream as a raw stream, not as a PrintStream, and send the bytes directly down this stream using the write() method.

Focus on Java (http://java.miningco.com/library/weekly/aa090299.htm) has a brief article describing the use of the Java 2 JPEGCodec class.

You can also use JIMI to read and write images in many formats, including GIF, JPEG, TIFF (TIF), PNG, PICT, Photoshop, BMP, Targa, ICO, CUR, Sunraster, XBM, XPM, and PCX.

See also: