Title: 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 the example to experiment with it and to see additional details.
|