This example shows how to matte one image onto another using an alpha channel. It also demonstrates a number of other useful techniques.
1
Creating the Background

First we create a Bitmap and draw our background onto it.

[C#]

using (Bitmap bitmap = (Bitmap)Bitmap.FromFile(Server.MapPath("rez/sam-schooler-E9aetBe2w40-unsplash.jpg")))


2
Creating the Foreground Image

Next we create the images we are going to draw onto our background. There are two parts here: the visible part and the alpha channel which defines a mask for the visible image. The visible part we set to yellow and then we insert an alpha channel using the SetAlpha function.

[C#]

using (Bitmap sun = new Bitmap(new Size())) {
  using (Bitmap mask = (Bitmap)Bitmap.FromFile(Server.MapPath("rez/sunmask.png"))) {
    sun.Resize(mask.Size);
    using (Graphics graphics = Graphics.FromImage(sun))
      graphics.Clear(Color.Yellow);
    Effects.SetAlpha(sun, mask);
  }


3
Drawing the Images

We now draw our image matted into the background.

[C#]

  using (Graphics graphics = Graphics.FromImage(bitmap))
    graphics.DrawImage(sun, new RectangleF(new PointF(30, 30), sun.Size));


4
Saving

Finally we save the Bitmap as a JPEG file.

[C#]

  bitmap.Save(Server.MapPath("Using_An_Alpha_Channel_2.jpg"), ImageFormat.Jpeg);
}


5
Input and Output

These are the kinds of input image you might use and the kind of output image you might expect.


sam-schooler-E9aetBe2w40-unsplash.jpg


sunmask.png


Using_An_Alpha_Channel_2.jpg