Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Writing Image

In this example, we are using FileInputStream class to read image and ServletOutputStream class for writing this image content as a response. To make the performance faster, we have used BufferedInputStream and BufferedOutputStream class.

You need to use the content type image/jpeg.

In this example, we are assuming that you have java.jpg image inside the c:\test directory. You may change the location accordingly.

To create this application, we have created three files:

  1. index.html
  3. web.xml


This file creates a link that invokes the servlet. The url-pattern of the servlet is servlet1.

  1. <a href=“servlet1”>click for photo</a>

This servlet class reads the image from the mentioned directory and writes the content in the response object using ServletOutputStream and BufferedOutputStream classes.

  1. package com.Kreationnext;
  2. import*;
  3. import javax.servlet.*;
  4. import javax.servlet.http.*;
  5. public class DisplayImage extends HttpServlet {
  6.     public void doGet(HttpServletRequest request,HttpServletResponse response)
  7.              throws IOException
  8.     {
  9.     response.setContentType(“image/jpeg”);
  10.     ServletOutputStream out;
  11.     out = response.getOutputStream();
  12.     FileInputStream fin = new FileInputStream(“c:\\test\\java.jpg”);
  13.     BufferedInputStream bin = new BufferedInputStream(fin);
  14.     BufferedOutputStream bout = new BufferedOutputStream(out);
  15.     int ch =0; ;
  16.     while((!=-1)
  17.     {
  18.     bout.write(ch);
  19.     }
  20.     bin.close();
  21.     fin.close();
  22.     bout.close();
  23.     out.close();
  24.     }
  25. }