java - 用Java编码透明动画gif

标签 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 获取透明颜色信息,但我不知道如何。

最佳答案

我正在使用以下解决方案,尽管仍然有一些 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);

关于java - 用Java编码透明动画gif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10950041/

相关文章:

java - 为什么我会收到输入无效无限循环?

Javascript 图像平移/缩放

css - 背景 CSS 图像

ios - 在当前上下文中以模态方式呈现时,在展开时,不会调用 viewDidAppear

delphi - 随着 Alpha 降低,在玻璃背景上绘制的文本变得模糊

java - 映射上的 REST api 404

java - @SessionAttributes 给出 HttpSessionRequiredException

php服务器和sql图片上传

php - 删除图像 -> codeigniter

java - 单选按钮在 JSP/Java 中没有响应