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

标签 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)第一个和第三个是正确的,保留了透明度,但中间一个将所有透明像素设置为黑色。我不确定我做错了什么,据我所知,最后两行应该是等价的。

这是我正在谈论的示例程序:

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");
        }
    }
}

最佳答案

你的最后一行

copy.Save("copy3.gif");

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

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

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

关于c# - .NET 中的透明度和 GIF——不一致的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8054225/

相关文章:

c# - 打破一个返回列表c#的函数

java - 一堆图像的 ImageJ 亮度和对比度

c# - List.Except 方法返回错误结果

C# 错误 - 找不到命名空间 ManagementClass、ManagementObject 和 ManagementObjectCollection

c# - 更新列表中的子项目会更新 C# 中的所有项目

c# - Json.NET 在返回 json 序列化字符串时添加反斜杠

image - 如何改进我的图像比较算法

python - 找到 map 中每个像素的最近邻居

c# - ASP.NET MVC 4 中 Controllers 目录中的文件夹

c# - 将 C++ 枚举导入 C#