Search code examples
javabufferedimagejava-ioanimated-gifjavax.imageio

Write animated-gif stored in BufferedImage to java.io.File Object


I am reading a gif image from internet url.

// URL of a sample animated gif, needs to be wrapped in try-catch block
URL imageUrl = new Url("http://4.bp.blogspot.com/-CTUfMbxRZWg/URi_3Sp-vKI/AAAAAAAAAa4/a2n_9dUd2Hg/s1600/Kei_Run.gif");

// reads the image from url and stores in BufferedImage object.
BufferedImage bImage = ImageIO.read(imageUrl);

// creates a new `java.io.File` object with image name
File imageFile = new File("download.gif");

// ImageIO writes BufferedImage into File Object
ImageIO.write(bImage, "gif", imageFile);

The code executes successfully. But, the saved image is not animated as the source image is.

I have looked at many of the stack-overflow questions/answers, but i am not able to get through this. Most of them do it by BufferedImage frame by frame which alters frame-rate. I don't want changes to the source image. I want to download it as it is with same size, same resolution and same frame-rate.

Please keep in mind that i want to avoid using streams and unofficial-libraries as much as i can(if it can't be done without them, i will use them).

If there is an alternative to ImageIO or the way i read image from url and it gets the thing done, please point me in that direction.


Solution

  • There is no need to decode the image and then re-encode it.

    Just read the bytes of the image, and write the bytes, as is, to the file:

    try (InputStream in = imageUrl.openStream()) {
        Files.copy(in, new File("download.gif").toPath());
    }