将 JAR 文件中的动画 gif 加载到 ImageIcon [英] Loading animated gif from JAR file into ImageIcon

查看:55
本文介绍了将 JAR 文件中的动画 gif 加载到 ImageIcon的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a ImageIcon from a animated gif stored in a jar file.

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

图像已加载,但仅加载了动画 gif 的第一帧.动画不播放.

The image loads, but only the first frame of the animated gif. The animation does not play.

如果我从文件系统上的文件加载动画 gif,一切都会按预期进行.动画播放所有帧.所以这是有效的:

If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:

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

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

How can I load an animated gif into an ImageIcon from a jar file?

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

Here is a complete test case, why doesn't this display the animation?

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 动画

This reads gif animation from inputStream

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

这篇关于将 JAR 文件中的动画 gif 加载到 ImageIcon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆