C#: Draw one Bitmap onto Another, with Transparency

31,889

Solution 1

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

Solution 2

Specify the transparency color of your small bitmap. e.g.

Bitmap largeImage = new Bitmap();
Bitmap smallImage = new Bitmap();
--> smallImage.MakeTransparent(Color.White);
Graphics g = Graphics.FromImage(largeImage);
g.DrawImage(smallImage, new Point(10,10);
Share:
31,889

Related videos on Youtube

Paul A Jungwirth
Author by

Paul A Jungwirth

Freelance web developer specializing in Rails, Postgres, and DevOps.

Updated on September 22, 2020

Comments

  • Paul A Jungwirth
    Paul A Jungwirth over 3 years

    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.

  • Paul A Jungwirth
    Paul A Jungwirth almost 14 years
    No, it's already converting white to transparent. The problem is the transparent cuts all the way through both images.