如何在 Java 中创建动画 gif?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5349750/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:43:41  来源:igfitidea点击:

How can I create animated gif in Java?

javaanimated-gif

提问by MaXal

I would like to create a gif image from the set of BufferedImages. How can I do this? Is there such library in pure Java (ImageMagick is not an option)? I've found Gif4J library but it's not royality-free.

我想从一组 BufferedImages 创建一个 gif 图像。我怎样才能做到这一点?纯 Java 中是否有这样的库(ImageMagick 不是一个选项)?我找到了 Gif4J 库,但它不是免版税的。

回答by Tony

I just answer a similar question here, but I think that my solution can help.

我只是在这里回答一个类似的问题,但我认为我的解决方案可以提供帮助。

'ImageIcon' class allows you to load gif animations. I load the image with 'getResource()'. For doing this I normally us URL class to pass the file path. The path does not need to be necessary in a remote machine as the name URL may suggest.

'ImageIcon' 类允许您加载 gif 动画。我用“getResource()”加载图像。为此,我通常使用 URL 类来传递文件路径。路径在远程机器中不需要,因为名称 URL 可能暗示。

URL url = This.class.getResource(path);
Icon myImgIcon = new ImageIcon(url);
JLabel imageLbl = new JLabel(myImgIcon);
component.add(imageLbl, BorderLayout.CENTER);

path will be the path of the gif inside of the class folder.

path 将是类文件夹内 gif 的路径。

References: http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html#getresource

参考资料:http: //docs.oracle.com/javase/tutorial/uiswing/components/icon.html#getresource

回答by Nevermore

There is an image processing library, akin to Picassowhich uses the very same AnimatedGifEncoder class mentioned by Lifelogger- Glide Docs, Glide

有一个图像处理库,类似于Picasso,它使用 Lifelogger- Glide Docs 中提到的相同 AnimatedGifEncoder 类 ,Glide

 AnimatedGifEncoder e = new AnimatedGifEncoder();
 e.start(outputFileName);
 e.setDelay(1000);   // 1 frame per sec
 e.addFrame(image1);
 e.addFrame(image2);
 e.finish();