在Java中编码透明的gif动画

问题描述 投票:1回答:2

我正在使用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获取透明的颜色信息,但是我不知道如何。

java image transparency gif animated-gif
2个回答
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);

0
投票

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

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

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

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.