C#: Draw one Bitmap onto Another, with Transparency

Paul A Jungwirth picture Paul A Jungwirth · Jul 15, 2010 · Viewed 29.7k times · Source

I have two Bitmaps, named largeBmp and smallBmp. I want to draw smallBmp onto largeBmp, then draw the result onto the screen. SmallBmp's white pixels should be transparent. Here is the code I'm using:

public Bitmap Superimpose(Bitmap largeBmp, Bitmap smallBmp) {
    Graphics g = Graphics.FromImage(largeBmp);
    g.CompositingMode = CompositingMode.SourceCopy;
    smallBmp.MakeTransparent();
    int margin = 5;
    int x = largeBmp.Width - smallBmp.Width - margin;
    int y = largeBmp.Height - smallBmp.Height - margin;
    g.DrawImage(smallBmp, new Point(x, y));
    return largeBmp;
}

The problem is that the result winds up transparent wherever smallBmp was transparent! I just want to see through to largeBmp, not to what's behind it.

Answer

James Hart picture James Hart · Jul 15, 2010

CompositingMode.SourceCopy is the problem here. You want CompositingMode.SourceOver to get alpha blending.