本文介绍了为什么我从 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?).

好消息是,该解决方案既简单又会节省您的 CPU 周期.如果您只想发送存储在磁盘上的动画 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.

相反,只需执行以下操作:

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

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 图像没有动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:05