简体   繁体   English

使用Graphics.DrawImage()以透明度/ Alpha通道绘制图像

[英]Using Graphics.DrawImage() to Draw Image with Transparency/Alpha Channel

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 src is loaded from an image with transparencies (such as GIF) or an alpha channel (such as PNG). 除非从具有透明度(例如GIF)或Alpha通道(例如PNG)的图像加载src否则这似乎很有效。

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通道传输到新图像,然后在保存文件时保留它们?

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. 您可以清楚地看到蓝色背景,因此透明度有效。

I found this thread because I had the same problem (ie DrawImage didn't copy the alpha channel), but in my case it was simply because I overlooked that I used PixelFormat.Format32bppRgb instead of PixelFormat.Format32bppArgb . 我找到了这个帖子,因为我有同样的问题(即DrawImage没有复制alpha通道),但在我的情况下,这只是因为我忽略了我使用PixelFormat.Format32bppRgb而不是PixelFormat.Format32bppArgb So pretty much what Lukasz M said in the comments. 所以Lukasz M在评论中说的很多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM