Java – loads animation gifs from jar files into imageicon

I'm trying to create an imageicon from the animated GIF stored in the jar file

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

The image is loaded, but only the first frame of the animated GIF The animation cannot be played

If I load an animated GIF from a file on the file system, everything works as expected The animation plays all frames So do this:

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

How do I load an animation GIF from a jar file into imageicon?

Editor: This is a complete test case. Why not show 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();
        }
    }
}

Solution

This reads GIF animation from InputStream

InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IoUtils.toByteArray(in));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
***
下一篇>>