[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Give an image a transparent background in C#

[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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.