2

I have this following code in my servlet

 response.setContentType("image/gif");
 String filepath = "PATH//TO//GIF.gif";
 OutputStream out = response.getOutputStream();
 File f = new File(filepath);
 BufferedImage bi = ImageIO.read(f);
 ImageIO.write(bi, "gif", out);
 out.close();

This code is just returning first frame of the image.

How to achieve returning full GIF image ?

1 Answers1

8

Your GIF does not animate, because you are sending only the first frame to the client. :-)

Actually, you are, because ImageIO.read reads only the first frame (and a BufferedImage can only contain a single frame/image). You are then writing that single frame to the servlet output stream, and the result will not animate (it should be possible to create animating GIFs using ImageIO, but the code to do so will be quite verbose, see How to encode an animated GIF in Java, using ImageWriter and ImageIO? and Creating animated GIF with ImageIO?).

The good news is, the solution is both simple, and will save you CPU cycles. There's no need to involve ImageIO here, if you just want to send an animated GIF that you have stored on disk. The same technique can be used to send any binary content, really.

Instead, simply do:

response.setContentType("image/gif");
String filepath = "PATH//TO//GIF.gif";
OutputStream out = response.getOutputStream();

InputStream in = new FileInputStream(new File(filepath));
try {
    FileUtils.copy(in, out);
finally {
    in.close();
}

out.close();

FileUtils.copy can be implemented as:

public void copy(final InputStream in, final OutputStream out) {
    byte[] buffer = new byte[1024]; 
    int count;

    while ((count = in.read(buffer)) != -1) {
        out.write(buffer, 0, count);
    }

    // Flush out stream, to write any remaining buffered data
    out.flush();
}
Community
  • 1
  • 1
Harald K
  • 26,314
  • 7
  • 65
  • 111