How do I return an image from a servlet using ImageIO?
Author: Deron Eriksson
Description: This tutorial describes how to use the ImageIO class to return an image from a servlet.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20


Page:    1 2 >

Sometimes, returning an image from a servletW can be a useful thing. For example, a servlet can be used to generate a chart on the fly. Sometimes, it can even be useful to have a servlet read an image file and return the image in the response. For example, if you have a servlet return dynamic images, but it experiences a problem, instead of an error code, you might want to have the servlet return an error image that might say something in the image such as "that image can't be found". In this way, if your application expects an image on a particular page, you will have an image there rather than nothing.

There are different ways to read and write images. One way is to use the ImageIO class, which provides very simple methods to read and write images. The ImageServlet class below demonstrates this. It reads an image file, "avajavalogo.jpg", from the JavaSW web application's context directory and stores this as a BufferedImage. It gets a reference to the response object's OutputStream via a call to response.getOutputStream(). It then writes the BufferedImage to the output stream as a "jpg" image.

ImageServlet.java

package test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setContentType("image/jpeg");

		String pathToWeb = getServletContext().getRealPath(File.separator);
		File f = new File(pathToWeb + "avajavalogo.jpg");
		BufferedImage bi = ImageIO.read(f);
		OutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);
		out.close();

	}

}

My web application's file structure is shown below.

'tomcat-demo' project

(Continued on page 2)

Page:    1 2 >