.NET 中的透明度和 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");
}
}
}
I am trying to edit and save an image using the .net Bitmap class. Some of the pixels are transparent, and they get converted to black under certain circumstances. If I save the same image like this:
image.Save("copy1.png", System.Drawing.Imaging.ImageFormat.Png);
image.Save("copy2.gif", System.Drawing.Imaging.ImageFormat.Gif);
image.Save("copy3.gif");
(Image being originally a gif) the first and third are correct retaining the transparency, but the middle one sets all the transparent pixels to black. I'm not sure what I am doing wrong, AFAIK the last two lines should be equivalent.
Here is a sample program of what I am talking about:
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");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最后一行
不会保存为 gif 文件,而是保存为 png,因为扩展名不足以指定保存格式。
要制作透明 gif,请使用类似
您的代码正在创建新位图,可能会丢失原始 gif 信息。
Your last line
does not save as gif file, but as png, since the extension is not sufficient to specify the saving format.
To make a transparent gif, use something like
Your code is creating a new bitmap, possibly losing the original gif informations.