0

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.

rupinderjeet
  • 2,984
  • 30
  • 54

1 Answers1

3

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());
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • you're awesome. just want to ask if i exercise it with 1000 calls in a `for-loop`, will it work sequentially or i need `synchronized` block? – rupinderjeet Jul 03 '16 at 09:24
  • 1
    A for loop doesn't execute code in multiple threads. It just executes its body sequentially, in a single thread. So synchronization is useless. But even if you did execute that code in multiple threads, there is 0 shared state between threads, so there is nothing to synchronize access to. Synchronization is needed when mutiple concurrent threads access to shared mutable state. You don't have threads. You don't have state. – JB Nizet Jul 03 '16 at 09:27
  • 1
    I'm not sure what you mean by "exercise it", though. You mean executing the above code for 1000 different URLs, writing to 1000 different files, right? – JB Nizet Jul 03 '16 at 09:29