C#: Draw one Bitmap onto Another, with Transparency
Asked Answered
S

3

27

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.

Stadiometer answered 15/7, 2010 at 18:16 Comment(0)
M
29

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

Missing answered 15/7, 2010 at 18:23 Comment(0)
P
4

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);
Parabasis answered 15/7, 2010 at 18:21 Comment(1)
No, it's already converting white to transparent. The problem is the transparent cuts all the way through both images.Stadiometer
E
0

Winform copy image on top of another

    private void timerFFTp_Tick(object sender, EventArgs e)
    {
        if (drawBitmap)
        {
            Bitmap bitmap = new Bitmap(_fftControl.Width, _fftControl.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);   
            _fftControl.DrawToBitmap(bitmap, new Rectangle(0, 0, _fftControl.Width, _fftControl.Height));
            if (!fDraw)
            {
                bitmap.MakeTransparent();
                Bitmap fftFormBitmap = new Bitmap(_fftForm.BackgroundImage);
                Graphics g = Graphics.FromImage(fftFormBitmap);
                g.DrawImage(bitmap, 0, 0);
                _fftForm.BackgroundImage = fftFormBitmap;
            }
            else
            {
                fDraw = false;
                _fftForm.Width = bitmap.Width + 16;
                _fftForm.Height = bitmap.Height + 48;
                _fftForm.BackgroundImage = bitmap;
            }
        }
    }
Egidius answered 22/9, 2019 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.