我正在尝试从存储在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");

如何从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();
        }
    }
}
有帮助吗?

解决方案

这将从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("http://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);
    }
}

希望现在还不算太晚。

我设法以这种方式在我的JPanel中获得动画gif:

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.图像文件在jar中;
2. ImageIO.read()返回一个BufferedImage,它不会更新ImageObserver;
3.找到捆绑在jar文件中的图像的另一种方法是询问Java类加载器,即加载程序的代码,以获取文件。它知道事物的位置。

通过这样做,我能够在我的JPanel中获得我的动画gif,它就像一个魅力。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top