Java 使用 ImageIO 创建动画 GIF?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/777947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating animated GIF with ImageIO?
提问by Neil Coffey
Has anybody managed to convince ImageIO to write an animated GIF, and in particular setting the correct metadata? My first attempt is roughly as follows (where b1 and b2 are BufferedImages):
有没有人设法说服 ImageIO 编写动画 GIF,特别是设置正确的元数据?我的第一次尝试大致如下(其中 b1 和 b2 是 BufferedImages):
ImageTypeSpecifier spec = new ImageTypeSpecifier(b1);
ImageWriter wr = ImageIO.getImageWriters(spec, "GIF").next();
wr.setOutput(ImageIO.createImageOutputStream(new File("C:\Flashing.gif")));
ImageWriteParam param = wr.getDefaultWriteParam();
IIOMetadata meta = wr.getDefaultImageMetadata(spec, param);
wr.prepareWriteSequence(meta);
wr.writeToSequence(new IIOImage(b1, null, null), param);
wr.writeToSequence(new IIOImage(b2, null, null), param);
This appears to almost work, but:
这似乎几乎有效,但是:
- I clearly need to somehow set "proper" metadata to set the time between the images and ideally make them loop (I was naively hoping the default would do something sensible, but hey...)
- whatever metadata it is writing by default is obviously not quite right: the GIMP gives a couple of error messages when loading the file, although embedding the image in a test web page in Firefox does display the two images in very quick succession, which is tantilisingly close to what I want...
- 我显然需要以某种方式设置“适当的”元数据来设置图像之间的时间并理想地使它们循环(我天真地希望默认值会做一些明智的事情,但是嘿......)
- 它默认写入的任何元数据显然都不太正确:GIMP 在加载文件时会给出一些错误消息,尽管将图像嵌入到 Firefox 的测试网页中确实会非常快速地连续显示这两个图像,这是令人兴奋的接近我想要的...
If anyone has got writing animated GIFs from ImageIO to work and can share a snippet of working code or how to fix the above problems, it would be greatly appreciated!
如果有人从 ImageIO 编写动画 GIF 工作并且可以分享工作代码片段或如何解决上述问题,将不胜感激!
回答by Elliot Kroo
I ran across this question, and decided to try it out; It took a small but non-trivial amount create a usable class (thanks ax) -- so I thought I might share the code around: hereis a small class for creating an animated gif image from a number of other images. Archived version
我遇到了这个问题,并决定尝试一下;创建一个可用的类(感谢ax)花费了少量但非平凡的时间- 所以我想我可以分享代码: 这是一个用于从许多其他图像创建动画 gif 图像的小类。存档版本