.NET中的透明度和GIF - 行为不一致

时间:2011-11-08 17:01:58

标签: c# .net image-processing transparency gif

我正在尝试使用.net Bitmap类编辑和保存图像。一些像素是透明的,并且在某些情况下它们会转换为黑色。如果我像这样保存相同的图像:

image.Save("copy1.png", System.Drawing.Imaging.ImageFormat.Png);
image.Save("copy2.gif", System.Drawing.Imaging.ImageFormat.Gif);
image.Save("copy3.gif");

(图像原本是gif)第一个和第三个是正确保留透明度,但中间的一个将所有透明像素设置为黑色。我不确定我做错了什么,AFAIK最后两行应该是等价的。

以下是我所谈论的示例程序:

using System.Drawing;
using System.Net;

namespace TestGif
{
    class Program
    {
        static void Main(string[] args)
        {
            Bitmap bitmap = new Bitmap(WebRequest.Create(
                "http://rlis.com/images/column/ie_icon.gif")
                           .GetResponse()
                           .GetResponseStream());

            int width = bitmap.Width;
            int height = bitmap.Height;
            Bitmap copy = new Bitmap(width, height);
            var graphics = Graphics.FromImage(copy);
            graphics.DrawImage(bitmap, new Point(0, 0));
            copy.Save("copy1.png", System.Drawing.Imaging.ImageFormat.Png);
            copy.Save("copy2.gif", System.Drawing.Imaging.ImageFormat.Gif);
            copy.Save("copy3.gif");
        }
    }
}

1 个答案:

答案 0 :(得分:3)

你的最后一行

copy.Save("copy3.gif");

不保存为gif文件,而是保存为png,因为扩展名不足以指定保存格式。 要制作透明的gif,请使用类似

的内容
Color c = copy.GetPixel(0, 0);
copy.MakeTransparent(c);

您的代码正在创建一个新的位图,可能会丢失原始的gif信息。