使用 ImageIO 创建动画 GIF?
有没有人设法说服 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);
这似乎几乎可以工作,但是:
- 我显然需要以某种方式设置“正确的”元数据来设置图像之间的时间,并理想地使它们循环(我天真地认为)希望默认值会做一些明智的事情,但是嘿...)
- 默认情况下写入的任何元数据显然都不太正确:GIMP 在加载文件时给出了一些错误消息,尽管将图像嵌入到测试网页中Firefox 确实以非常快的速度连续显示这两个图像,这非常接近我想要的...
如果有人能够从 ImageIO 编写动画 GIF 并可以分享一段工作代码或如何解决上述问题,那么它将不胜感激!
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):
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...
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到了这个问题,决定尝试一下; 创建一个可用的类需要花费少量但不平凡的时间(感谢ax)——所以我想我可以分享代码: 这里是一个小类,用于从数字创建动画 gif 图像其他图像。 存档版本
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: here is a small class for creating an animated gif image from a number of other images. Archived version