2

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?

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Crimson Bloom
  • 287
  • 2
  • 13

1 Answers1

1

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.

Community
  • 1
  • 1
clearlyspam23
  • 1,624
  • 13
  • 15
  • How would I go about writing the data from the `DataInputStream` to a `ByteArrayOutputStream`? – Crimson Bloom Dec 18 '15 at 00:45
  • @CodedApple You should be able to do it by just replacing the line `FileOutputStream fo = new FileOutputStream(...);` with `ByteArrayOutputStream bo = new ByteArrayOutputStream();`. Then after you have written the gif to the stream, you can fetch the bytes by calling 'toByteArray'. Then, when you want to write those bytes into a file, just open up a new `FileOutputStream` and write the byte array into it. – clearlyspam23 Dec 18 '15 at 01:04