Crimson Bloom
Crimson Bloom

Reputation: 287

Store animated GIF image in a Java program

In a Java program you can store images like .png, .jpg and such in a BufferedImage. I don't think it works for animated gif images as it seems to lose its animation.

Currently I get normal images like:

BufferedImage image = ImageIO.read(new URL(images.get(x)));
String type = images.get(x).substring(images.get(x).length() - 3, images.get(x).length());
ImageIO.write(image, type, new File(title + "/" + filename));

Where images is a String[] of URLs.

As for gif's I'm getting them by:

byte[] b = new byte[1];
URL url = new URL(images.get(x));
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
DataInputStream di = new DataInputStream(urlConnection.getInputStream());

FileOutputStream fo = new FileOutputStream(title + "/" + filename);
while (-1 != di.read(b, 0, 1) && downloading)           
    fo.write(b, 0, 1);
di.close();
fo.close();

But I want to store them in the program and write them to a file another time. How do I store a GIF without writing it to a file but while keeping its animation?

Upvotes: 2

Views: 1634

Answers (1)

clearlyspam23
clearlyspam23

Reputation: 1694

If you are only interested in storing the gif in memory, and not in having it display from the java program. You could write the data you've received into a ByteArrayOutputStream rather than a FileOutputStream, and then take the resulting byte array and write that to a FileOutputStream at a later time.

If you would like to display the animated gif, you might want to check out the top answer in this post, although the first comment on the answer seems to be having a problem similar to yours.

Upvotes: 1

Related Questions