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



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

ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));

图像加载,但仅加载动画 GIF 的第一帧。 动画无法播放。

如果我从文件系统上的文件加载动画 gif,一切都按预期工作。 动画通过所有帧播放。 所以这有效:

ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");

如何将动画 gif 从 jar 文件加载到 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();
        }
    }
}

这会从inputStream读取gif动画

InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));

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

编辑:加载图像后,您必须设置 ImageObserver 属性才能运行动画。

由于这个线程只是从一个与动画 GIF 关系不大但被拖到 OT 的最新线程链接的,我想我会添加这个"对我有用"的琐碎来源。

import javax.swing.*;
import java.net.URL;
class AnimatedGifInLabel {
    public static void main(String[] args) throws Exception {
        final URL url = new URL("https://i.stack.imgur.com/OtTIY.gif");
        Runnable r = new Runnable() {
            public void run() {
                ImageIcon ii = new ImageIcon(url);
                JLabel label = new JLabel(ii);
                JOptionPane.showMessageDialog(null, label);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

希望现在还为时不晚。

我设法以这种方式将动画 gif 放入我的 JPanel 中:

private JPanel loadingPanel() {
    JPanel panel = new JPanel();
    BoxLayout layoutMgr = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
    panel.setLayout(layoutMgr);
    ClassLoader cldr = this.getClass().getClassLoader();
    java.net.URL imageURL   = cldr.getResource("img/spinner.gif");
    ImageIcon imageIcon = new ImageIcon(imageURL);
    JLabel iconLabel = new JLabel();
    iconLabel.setIcon(imageIcon);
    imageIcon.setImageObserver(iconLabel);
    JLabel label = new JLabel("Loading...");
    panel.add(iconLabel);
    panel.add(label);
    return panel;
}

这种方法的一些要点:
1.图像文件在罐子里;
2. ImageIO.read() 返回一个 BufferedImage,它不会更新 ImageObserver;
3. 查找捆绑在 jar 文件中的图像的另一种方法是要求 Java 类加载器(加载程序的代码)获取文件。它知道东西在哪里。

因此,通过这样做,我能够将我的动画gif放入我的JPanel中,它就像一个魅力。

最新更新