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();
}
}
}
You can load images (gif, jpg or png) with load("filename") from sketches folder. You can access the folder from IDE with ctrl-k or from menu Sketch->Open Sketch Folder.
ImageIcon icon = new ImageIcon("star. gif"); and attach it to a JLabel; JLabel starLabel = new JLabel(icon);
You can create your own animated GIFs using the Python programming language and the Pillow package.
Select File > Export. In the dialog box, set the File Format to GIF and specify where the finished file should be saved. Select Export.
This reads gif animation from inputStream
InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));
You have to use getClass().getResource(imgName); to get a URL to the image file. Check out this tutorial from Real's HowTo.
EDIT: Once the image is loaded you have to set the ImageObserver property to get the animation to run.
Since this thread was just linked from a more current thread that had little to do with animated GIFs but got dragged OT, I thought I'd add this trivial source that 'works for me'.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With