Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

java - Why is my gif image sent from servlet not animating?

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...