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();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…