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

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:

enter image description here

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:

enter image description here

You can clearly see the blue background so the transparency worked.

Leave a Comment