为什么我从servlet发送的gif图像没有动画? [英] Why is my gif image sent from servlet not animating?

查看:147
本文介绍了为什么我从servlet发送的gif图像没有动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的servlet中有以下代码

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.

如何实现返回完整的GIF图像?

How to achieve returning full GIF image ?

推荐答案

您的GIF没有动画,因为您只发送了第一帧到客户端。 : - )

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

实际上,你是,因为 ImageIO.read 只读取第一帧(和 BufferedImage 只能包含一个帧/图像。然后,您将该单帧写入servlet输出流,结果将不会生成动画(应该可以使用 ImageIO 创建动画GIF,但是这样做的代码将会非常详细,请参阅如何使用ImageWriter和ImageIO对Java中的动画GIF进行编码?使用ImageIO创建动画GIF?

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?).

好消息是,解决方案是既简单又省钱。如果您只想发送存储在磁盘上的动画GIF,则无需在此处涉及 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.

相反,只需执行:

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 可以实现为:

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

这篇关于为什么我从servlet发送的gif图像没有动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆