Home > Articles > Programming > Java

Generating Images in Java Servlets

📄 Contents

  1. Sending Image Files from Servlets
  2. Images from Drawings
  • Print
  • + Share This
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

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:


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.

package servletdemo;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.awt.Image;
import javax.swing.ImageIcon;
import Acme.JPM.Encoders.GifEncoder;

public class ImageContent extends HttpServlet {
 /** Process the HTTP Get request */
 public void doGet(HttpServletRequest request, HttpServletResponse
  response) throws ServletException, IOException {
  OutputStream out = response.getOutputStream();

  // Obtain an image icon
  ImageIcon imageIcon = new ImageIcon("c:\\radjb\\image\\" +
   request.getParameter("country") + ".gif");

  // Obtain image from image icon
  Image image = imageIcon.getImage(); // Get the image

  // Encode the image and send to the output stream
  new GifEncoder(image, out, true).encode();

  out.close(); // Close stream

Figure 1 The servlet returns an image of the country flag.

  • + Share This
  • 🔖 Save To Your Account