Generating Images in Java Servlets

Servlets are Java programs that run on a Web server. These Java servlets can be used to generate dynamic Web pages. What's more, the pages are not limited to text and thus can be images. Y. Daniel Liang demonstrates here how to generate images in Java servlets.

This article is derived from the book Rapid Java Application Development Using JBuilder 4/5/6 (Prentice Hall PTR, 2001), by Y. Daniel Liang.

From the author of

From the author of

Servlets are Java programs that run on a Web server. Java servlets can
be used to generate dynamic Web pages. The pages are not limited to text, and
they can be images. This article demonstrates generating images in Java
serlvets.

Sending Image Files from Servlets

To send contents as images, the content type must be set to image/gif,
image/jpg, or image/png. For example, to send GIF images, you need to set the
content type as follows:

response.setContentType("image/gif");

Here, response is an instance of HttpServletResponse.
Because images are binary data, you have to use a binary output stream:

OutputStream out = response.getOutputStream();

You can then create an instance of the Image class filled with
content. Before the image is sent to a browser, it must be encoded into a format
acceptable to the browser. Image encoders are not part of Java API, but several
free encoders are available. One of them is the
GifEncoder class
from Acme.

Use the following statement to encode and send the image to the browser:

new GifEncoder(image, out, true).encode();

Here is an example of a servlet that dynamically generates the flag of a
country, as shown in Figure 1.