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

查看:860
本文介绍了如何使用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.)

推荐答案

以下是 GIFanim createImage()方法一>。也许这会给你一个开始。

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天全站免登陆