如何使用 ImageWriter 和 ImageIO 在 Java 中编码动画 GIF? [英] How to encode an animated GIF in Java, using ImageWriter and ImageIO?

查看:25
本文介绍了如何使用 ImageWriter 和 ImageIO 在 Java 中编码动画 GIF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找遍了所有地方,但似乎找不到任何易于理解的解释.(我发现其他 Java 用户编写的类和方法可以做到这一点,但我希望自己编写.)

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.)

推荐答案

这里是createImage()方法"nofollow">GIFanim.也许这会给你一个开始.

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.

这篇关于如何使用 ImageWriter 和 ImageIO 在 Java 中编码动画 GIF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆