Writing an animated gif from BufferedImages
Asked Answered
P

1

2

I have a program that loads a spritesheet, creates BufferedImages of each frame on the sheet, and writes it to an animated gif. Using the class provided by Elliot Kroo on Creating animated GIF with ImageIO?, I was able to successfully output a file. However, the gif doesn't animate quite right. The sheet I provided was a .png with a transparent background, so every subsequent frame is just put on top of the last frames, with differences showing through the transparent background (Example). Here's the code that uses the gif writer:

ImageOutputStream output = new FileImageOutputStream(new File(savePath));
GifSequenceWriter writer = new GifSequenceWriter(output, data[0].getType(), delay, true);
for(BufferedImage bi:data)
{
    writer.writeToSequence(bi);
}
writer.close();
output.close();

Where data is an array of each frame as a BufferedImage (which I have also checked, and don't seem to be the problem). Is this a limitation of .gifs or the Java ImageWriters? Or can I edit a setting somewhere to prevent this? I'd rather not put a background if I don't have to.

Puncheon answered 6/8, 2011 at 15:27 Comment(0)
V
2

Assuming data is an array of BufferedImage, the imageType parameter to the GifSequenceWriter constructor would likely be TYPE_INT_ARGB for data read from a .png file. I would expect transparentColorFlag to be true, but you'd have to determine the transparentColorIndex empirically.

graphicsControlExtensionNode.setAttribute("transparentColorFlag", "TRUE");
graphicsControlExtensionNode.setAttribute("transparentColorIndex", ???);

See also this answer.

Vanhouten answered 6/8, 2011 at 19:2 Comment(5)
Ah. Is there no way to edit the behavior of the gifwriter to not use the optimized frames? Also, the color for the transparent background seemed to be black(0,0,0), but passing 0 for the transparentColorIndex doesn't seem to affect anything(not even the normal black goes away).Puncheon
Not as far as I know. Kroo's code seems to assume opaque images. A .gif lacks an alpha channel; it only has a color index meant to be interpreted as transparent. If you need to preserve the .png transparency, you might try this AnimatedGifEncoder.Vanhouten
Do you know what I should assign the attribute transparentColorIndex? It doesn't seem to be an int with ARGB color.Puncheon
Right, transparentColorIndex isn't a color; it's an index in the .gif color table; it would be whatever color your encoder chooses, e.g. findClosest(). Note that GifSequenceWriter` uses the ImageIO encoder, while AnimatedGifEncoder does its own encoding.Vanhouten
findClosest() is a method of AnimatedGifEncoder, which does its own encoding. I doesn't use the ImageIO encoder.Vanhouten

© 2022 - 2024 — McMap. All rights reserved.