C# 使用 Graphics.DrawImage() 绘制带有透明度/Alpha 通道的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10658994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Graphics.DrawImage() to Draw Image with Transparency/Alpha Channel
提问by Jonathan Wood
I'm copying an image. (My actual code is resizing the image but that's not relevant to my question.) My code looks something like this.
我正在复制图像。(我的实际代码正在调整图像大小,但这与我的问题无关。)我的代码看起来像这样。
Image src = ...
using (Image dest = new Bitmap(width, height))
{
Graphics graph = Graphics.FromImage(dest);
graph.InterpolationMode = InterpolationMode.HighQualityBicubic;
graph.DrawImage(src, 0, 0, width, height);
dest.Save(filename, saveFormat);
}
This seems to work great unless srcis loaded from an image with transparencies (such as GIF) or an alpha channel (such as PNG).
除非src从带有透明胶片(例如 GIF)或 alpha 通道(例如 PNG)的图像加载,否则这似乎效果很好。
How can I get DrawImage()to transfer the transparencies/alpha channel to the new image, and then keep them when I save the file?
如何DrawImage()将透明胶片/Alpha 通道传输到新图像,然后在保存文件时保留它们?
采纳答案by Hans Passant
It is pretty unclear, there's a lot you didn't say. The biggest issue with transparency is that you can't see it. You skipped a couple of steps, you didn't explicitly specify the pixel format of your new bitmap, you didn't initialize it at all and you didn't say what output format you use. Some don't support transparency. So let's make a version that makes it crystal clear. From a PNG image that looks like this in paint.net:
说的不是很清楚,有很多你没说。透明度的最大问题是你看不到它。您跳过了几个步骤,您没有明确指定新位图的像素格式,您根本没有初始化它,也没有说明您使用什么输出格式。有些不支持透明度。因此,让我们制作一个使其清晰的版本。从paint.net中看起来像这样的PNG图像:


Using this code
使用此代码
using (var src = new Bitmap("c:/temp/trans.png"))
using (var bmp = new Bitmap(100, 100, PixelFormat.Format32bppPArgb))
using (var gr = Graphics.FromImage(bmp)) {
gr.Clear(Color.Blue);
gr.DrawImage(src, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save("c:/temp/result.png", ImageFormat.Png);
}
Produces this image:
生成此图像:


You can clearly see the blue background so the transparency worked.
您可以清楚地看到蓝色背景,因此透明度起作用。
回答by Alex
I found this thread because I had the same problem (i.e. DrawImage didn't copy the alpha channel), but in my case it was simply because I overlooked that I used PixelFormat.Format32bppRgbinstead of PixelFormat.Format32bppArgb. So pretty much what Lukasz M said in the comments.
我发现这个线程是因为我有同样的问题(即 DrawImage 没有复制 alpha 通道),但在我的情况下,这仅仅是因为我忽略了我使用PixelFormat.Format32bppRgb而不是PixelFormat.Format32bppArgb. Lukasz M 在评论中所说的差不多。

