问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/6967809/writing-an-animated-gif-from-bufferedimages