How to encode an animated GIF in Java, using ImageWriter and ImageIO?

对着背影说爱祢 提交于 2019-12-02 11:58:11

问题


I've looked all over the place, but can't seem to find any easy to understand explanation. (I've found classes and methods written by other Java users that can do this, but I'm hoping to write my own.)


回答1:


Here is the createImage() method of GIFanim. Perhaps that will give you a start.

public byte[] createImage() throws Exception {

    ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    iw.setOutput(ios);
    iw.prepareWriteSequence(null);
    int i = 0;

    for (AnimationFrame animationFrame : frameCollection) {

        BufferedImage src = animationFrame.getImage();
        ImageWriteParam iwp = iw.getDefaultWriteParam();
        IIOMetadata metadata = iw.getDefaultImageMetadata(
            new ImageTypeSpecifier(src), iwp);

        configure(metadata, "" + animationFrame.getDelay(), i);

        IIOImage ii = new IIOImage(src, null, metadata);
        iw.writeToSequence(ii, null);
        i++;
    }

    iw.endWriteSequence();
    ios.close();
    return os.toByteArray();
}

Note that this is a very naïve implementation, that produces images that are significantly larger than can be made with a library that compresses the color palette and performs other optimizations. Implementing a library like that would be a significant task.



来源:https://stackoverflow.com/questions/8549460/how-to-encode-an-animated-gif-in-java-using-imagewriter-and-imageio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!