Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

java - Loading animated gif from JAR file into 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")));

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

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");

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

EDIT: 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();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This reads gif animation from inputStream

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...