Servlet Send Image as Response

Prev Tutorial Next Tutorial

Send Image as Response in Servlet

To Send an image as response from servlet back to the browser the following changes are required.

  • Set MIME type or content type as image by using image/.gif.
  • To transfer image response, you need ServletOutputStream as an outputStream to write the response. In this case printWriter class is not suitable.
  • Use an image encoder class, to store that image file into the outputStream object.


import javax.servlet.*;  
import javax.servlet.http.*;  
import java.awt.image;
import javax.swing.imageIcon.*;  
import Acme.JpmEncoders.GifEncoder;  

public class MyServlet extends HttpServlet
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    ServletOutputStream out = response.outputStream();  
    // optain image icon
	ImageIcon imageicon=new ImageIcon("c:/cow.gif");

	// encoding the image and send to the outputStream

	GifEncoder g=new GifEncoder(image, out)


In the above servlet program you have need to use third party class called GifEncoder, so you need a jar file to set in the classpath called acme.jar

To compile the above servlet you need the flowing jar files.

  • servlet-api.jar
  • acme.jar

You need to copy acme.jar file into the lib folder to execute above servlet program





Prev Tutorial Next Tutorial

Download Projects

Google Adsense Advertisements
Free Classified Site – Bedpage

Yahoo Advertisements