将JAR文件中的动画gif加载到ImageIcon中

Ste*_*e K 9 java swing animated-gif javax.imageio

我正在尝试从存储在jar文件中的动画gif创建一个ImageIcon.

ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
Run Code Online (Sandbox Code Playgroud)

图像加载,但只加载动画gif的第一帧.动画无法播放.

如果我从文件系统上的文件加载动画gif,一切都按预期工作.动画播放所有帧.这样可行:

ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
Run Code Online (Sandbox Code Playgroud)

如何从jar文件中将动画gif加载到ImageIcon中?

编辑:这是一个完整的测试用例,为什么不显示动画?

import javax.imageio.ImageIO;
import javax.swing.*;

public class AnimationTest extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                AnimationTest test = new AnimationTest();
                test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                test.setVisible(true);
            }
        });
    }

    public AnimationTest() {
        super();
        try {
            JLabel label = new JLabel();
            ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
            label.setIcon(imageIcon);
            imageIcon.setImageObserver(label);
            add(label);
            pack();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

这将从inputStream中读取gif动画

InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));
Run Code Online (Sandbox Code Playgroud)


Bil*_*ard 6

你必须使用getClass().getResource(imgName); 获取图像文件的URL.从Real的HowTo 查看本教程.

编辑:加载图像后,您必须设置ImageObserver属性以使动画运行.