Give an image a transparent background in C#


The Bitmap class’s MakeTransparent method changes all of the pixels with a given color to the transparent color A = 0, R = 0, G = 0, B = 0. When the program starts, the following code makes the background transparent for the two images stored in the program’s Smile and Frown resources.

// The images.
private Bitmap SmileBitmap, FrownBitmap;

// Make the images' backgrounds transparent.
private void Form1_Load(object sender, EventArgs e)
    SmileBitmap = Properties.Resources.Smile;
    SmileBitmap.MakeTransparent(SmileBitmap.GetPixel(0, 0));

    FrownBitmap = Properties.Resources.Frown;
    FrownBitmap.MakeTransparent(FrownBitmap.GetPixel(0, 0));

The code saves the Smile resource in a Bitmap variable. It then uses the Bitmap object’s MakeTransparent method to make all of its pixels that match the color of the pixel in the upper left corner transparent. The code then repeats those steps for the Frown image.

The following Paint event handler displays the two images.

// Draw the two images overlapping.
private void Form1_Paint(object sender, PaintEventArgs e)
    e.Graphics.DrawImage(FrownBitmap, 30, 30);
    e.Graphics.DrawImage(SmileBitmap, 95, 85);

This code simply draws the two images overlapping so you can see that they have transparent backgrounds.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in graphics, image processing and tagged , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Give an image a transparent background in C#

  1. kaliprasad m says:


    Is there a way make the gray transparent to White ?

    • RodStephens says:

      I’m not sure what you’re asking. In this example, the background is transparent. It is drawn over a gray background, so that is what is showing through. if you display it on a white background, then the white would show through.

      If you’re asking whether you can make the white pixels in the image transparent, simply call the bitmap’s MakeTransparent method and pass it the color Color.White.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.