在Java中编码透明动画gif

时间:2012-06-08 13:44:13

标签: java image transparency gif animated-gif

我正在使用GifDecoder来读取动画.gif文件,并使用AnimGifEncoder来编写它。 (link

如果我显示由GifDecoder读取的原始帧,它们会正确显示并且是透明的,但如果我显示由AnimatedGifEncoder创建的帧,则透明度完全错误。

   GifDecoder gif = new GifDecoder();
   gif.read("image.gif");

   AnimatedGifEncoder e = new AnimatedGifEncoder();
   e.start("newimage.gif");
   e.setTransparent(Color.BLACK);

   for (int i=0;i<gif.getFrameCount();i++) {
        anim.addFrame(gif.getFrame(i));
        anim.setDelay(gif.getDelay(i));
   }

   anim.finish();

在此示例中,我将透明色设置为黑色。但实际上我想从GifDecoder获取透明的颜色信息,但我不知道如何。

2 个答案:

答案 0 :(得分:1)

我正在使用以下解决方案,尽管仍有一些gif文件 缩放后是一团糟......:

(至少它似乎与大多数不透明的GIF相处)

Color transparentColor = null;
BufferedImage firstFrameImage = ImageIO.read([sourceFileHere]);

if (firstFrameImage.getColorModel() instanceof IndexColorModel) {
   IndexColorModel cm = (IndexColorModel) firstFrameImage.getColorModel();
   int transparentPixel = cm.getTransparentPixel();
   transparentColor = new Color(cm.getRGB(transparentPixel), true);
}

e.setTransparent(transparentColor);

答案 1 :(得分:0)

这是很久以前的事了,但是我当时确实设法使它工作了。无需再次挖掘代码...我的工作方式是:

  1. 扫描原始图像并将透明区域设置为原始图像内部不存在的颜色。

  2. 将AnimGifEncoder内部的透明颜色设置为先前分配给透明区域的颜色。