Gif Animado

8 respostas
S

Alguém sabe a classe correta para exibir um GIF animado dentro de um JLabel?

8 Respostas

Spammer
public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("C:\downloads\dance.gif");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);

        JFrame f = new JFrame("Animation");
        f.getContentPane().add(label);
        // e continua o codigo para baixo
S

Cara este código funciona apenas para imagens estáticas tipo png e jpg, para gif animados ele não funciona.

botocudo_killer
public class TestGif {

    private JFrame frame;
    private URL url = null;

    public ArrayList<BufferedImage> getFrames(URL gif) throws IOException{
        ArrayList<BufferedImage> frames = new ArrayList<BufferedImage>();
        ImageReader ir = new GIFImageReader(new GIFImageReaderSpi());
        URLConnection urlconnection = gif.openConnection();
        ir.setInput(ImageIO.createImageInputStream(urlconnection.getInputStream()), false);
        for(int i = 0; i < ir.getNumImages(true); i++){
            ImageReadParam param = ir.getDefaultReadParam();
            frames.add(ir.read(i, param));
        }
        return frames;
    }

    public TestGif() throws FileNotFoundException {
        frame = new JFrame("teste");
        try {
            url = new URL("");
        } catch (MalformedURLException ex) {
            Logger.getLogger(TestGif.class.getName()).log(Level.SEVERE, null, ex);
        }

        List<GifFrame> gifFrames = new ArrayList<GifFrame>();
        ArrayList<BufferedImage> images = null;
        try {
            images = getFrames(url);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        for(BufferedImage image: images)
        {
            int transparantColor = image.getRGB(0, 0); // purple
            BufferedImage gif = ImageUtil.convertRGBAToGIF(image, transparantColor);
            long delay = 100; // every frame takes 100ms
            String disposal = GifFrame.RESTORE_TO_BGCOLOR; // make transparent pixels not 'shine through'
            gifFrames.add(new GifFrame(gif, delay, disposal));
        }

        OutputStream outputStream = new FileOutputStream("C:\\Documents and Settings\\DEVELOPER\\Desktop\\suaimagem.gif");

        int loopCount = 0; // loop indefinitely
        try {
            ImageUtil.saveAnimatedGIF(outputStream , gifFrames, loopCount);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ImageIcon icon = null;
        try {
            icon = new ImageIcon(new File("C:\\Documents and Settings\\DEVELOPER\\Desktop\\suaimagem.gif").toURI().toURL());
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JLabel label = new JLabel(icon);
        icon.setImageObserver(label);
        frame.getContentPane().add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                try {
                    new TestGif();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}
S

Muito estranho, eu já fiz isso com classes nativas do Java, algo em torno de 3 ou 4 linhas sem nenhum jar de terceiros. Infelizmente não tenho mais o código, mas tenho certeza que existe alguma forma.

BooT_SJRP

Esta usando o NetBeans?
Voce pode utilizar apenas o ambiente grafico, criando um pacote ( imagens por exemplo ), dai coloca o gif dentro deste pacote. Depois na propriedade do JLabel coloca como ICON o gif dentro do pacote.

S

ele aparece animado ou estático? utilizo o eclipse, mas se isso realmente funcionar vou utilizar o netbeans apenas para descobrir o nome da classe correta.

BooT_SJRP

Ele aparece animado.
Segue um exemplo.

Spammer

veja este link talvez ajude alvinalexander

Criado 19 de outubro de 2012
Ultima resposta 19 de out. de 2012
Respostas 8
Participantes 4