问题
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).
How can I get DrawImage()
to transfer the transparencies/alpha channel to the new image, and then keep them when I save the file?
回答1:
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:
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.
回答2:
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.Format32bppRgb
instead of PixelFormat.Format32bppArgb
. So pretty much what Lukasz M said in the comments.
来源:https://stackoverflow.com/questions/10658994/using-graphics-drawimage-to-draw-image-with-transparency-alpha-channel