如何使用Java从URL下载动画gif? [英] How to download animated gif from URL with Java?

查看:58
本文介绍了如何使用Java从URL下载动画gif?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了很多,但是,我所能得到的只是第一张图片,而不是动画的gif.

I have tried a lot but, all i can get is just the first image and not the animated gif.

目前最好的解决方案是将动画gif加载到图标中,但是我需要该文件.这里的代码:

The best solution at the moment was load an animated gif into icon, but i need the file. Here the code:

final URL url = new URL("http://www.freeallimages.com/wp-content/uploads/2014/09/animated-gif-images-2.gif");

JLabel l = new JLabel(new ImageIcon(url));
JOptionPane.showMessageDialog(null, l);

有人可以在这里帮助吗?

Can anyone help here?

此代码仅获取gif的第一张图片(未动画处理):

This code just get the first image of gif (not animated):

public static void saveImage(String imageUrl, String destinationFile) throws IOException {
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    File file = new File(destinationFile);
    file.getParentFile().mkdirs();
    file.createNewFile();
    OutputStream os = new FileOutputStream(destinationFile );

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

推荐答案

就代码而言,这很好,应该正确下载GIF.(比较原始GIF和下载的GIF大小以进行确认).现在有两点:

1. Windows Photo Viewer无法显示动画的GiF,请使用Internet Explorer代替它.
2.在Java中,不要使用Event-Dispatcher线程来显示任何动画GIF,因为它肯定不会动画.尝试使用其他线程显示包含动画GIF的任何帧.

As far as the code is concerned, it is fine and the GIF should get downloaded properly.(Compare sizes of the original and downloaded GIF for confirmation). Now there are two points:

1. Windows Photo Viewer can not display animated GiF's, use Internet Explorer instead of it.
2. In java do not use Event-Dispatcher thread to display any animated GIF, it will not animate for sure. Try using another thread for displaying any frame containing animated GIF.

从代码中可以清楚地看出,在使用动画GIF初始化JLabel之后,您已经从JOptionPane初始化了一个对话框,请不要这样做.JOptionPane中的所有对话框都是模态的,它将阻止您当前的线程执行,因此您将看不到任何动画.

As is clear from your code, you have initialized a dialog from JOptionPane soon after initializing a JLabel with animated GIF, don't do this. All dialogs in JOptionPane are modal which will block your current thread execution and therefore you will not see any animation.

这篇关于如何使用Java从URL下载动画gif?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆