Display images with "<IMG SRC=" where "SRC" is a Java servlet. I got it working for JPG's, but not GIF's.

Posted on 2006-04-18
Last Modified: 2013-11-24
I'm an intermediate level Java servlet programmer (i.e, I know just enough to get by, without delving into the details).  Anyhoo, I have images that I want only my servlets to display to the browser.  The code I have written below (it's a stripped down version for this posting) works just fine when displaying JPG images via the "<IMG SRC..." tags that are written in my PrintWriter output.  

But for the life of me, I can't find equivalent code that renders GIF files.  I've heard of the Jimi and ACME environments, but do I really need to implement an entire graphics environment for this seemingly easy task??   (And besides, I've downloaded both those packages, and STILL can't seem to get it to work!).

If possible, can someone simply provide the equivalent code as what I've offered below, but to work with GIF images.  I've tried long enough, so need some help.



package mypackage;

import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.BufferedImage;

public class JpegView extends HttpServlet {

  private final static String IMG_TOKEN = "img";

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

    String fName = request.getParameter( IMG_TOKEN );
    File f = new File( "/home/content/m/y/a/myaccountfolder/non_public_folder/" + fName );

    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new FileInputStream(f));
    BufferedImage image =decoder.decodeAsBufferedImage() ;
    ServletOutputStream sos = response.getOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);

  public static String ImgSrc( String fName ) {
    return "<IMG SRC=\""
                     + "?" + IMG_TOKEN + "=" + fName + "\">";
Question by:stockblocks
    LVL 23

    Accepted Solution

    LVL 14

    Expert Comment

    by:Tommy Braas
    You are not setting the content type for the response.

    Author Comment

    orangehead911 (regarding your comment on not setting content type in response)...

      I agree -- it should be added.   But the JPG's are still rendered even with that line excluded.  I'm not sure why... perhaps my browser is smart enough to assume what it is.  But I'm getting off track. I'm more interested in figuring out how to get similar code working with GIF's.


    Author Comment


    Your reference to ch09-05.htm was the info I needed.  I adapted it to read from a file (versus database retrieval that page pertained to), and it works.  It's just as simple as I had hoped for.

    FYI, the code I used to test it is below.

    For kicks, I recompiled with the code WITHOUT calling response.setContentType("image/gif"), and the GIF file still displayed properly!  Why is this?  Same question with my original JPG code (i.e., I didn't include setContentType("image/jpg"), and yet the JPG files were still displayed).  Does this make sense?  I presume it would be wise to include those lines anyway.   Please let me know your thoughts on this.

    Thanks again.



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

        String fName = request.getParameter( IMG_TOKEN );
        File f = new File( disk path...  + "/" + fName );
        int fileSize = (int)f.length();

     // response.setContentType("image/gif");    <--- GIF rendered even WITHOUT this line

        ServletOutputStream out = response.getOutputStream();

        BufferedInputStream gifData = new BufferedInputStream( new FileInputStream( f ) );

        byte[] buf = new byte[4 * 1024];  // 4K buffer
        int len;
         while ((len =, 0, buf.length)) != -1) {
            out.write(buf, 0, len);

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    One of the typical problems I have experienced is when you have to move a web server from one hosting site to another. You normally prepare all on the new host, transfer the site, change DNS and cross your fingers hoping all will be ok on new server…
    International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
    Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
    This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now