Loading animated gif from JAR file into ImageIcon

Steve K picture Steve K · Sep 29, 2008 · Viewed 14.6k times · Source

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();
        }
    }
}

Answer

Penkov Vladimir picture Penkov Vladimir · Jun 28, 2011

This reads gif animation from inputStream

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