views:

843

answers:

3

I have an object of the type System.Drawing.Image and want to make every pixel which has some specific color, for example black, transparent (that is, set alpha to 0 for this pixel).

What is the best way to do this?

A: 

Do you only know that it's an Image? If it's a Bitmap, you could call LockBits, check/fix every pixel and then unlock the bits again.

Jon Skeet
+2  A: 

Construct a Bitmap from the Image, and then call MakeTransparent() on that Bitmap. It allows you to specify a colour that should be rendered as transparent.

Martin
MakeTransparent will work, but most likely you want to write a function that does the same thing but operates with a tolerance. This makes for smoother blending in compositing.
plinth
Thanks, I ended up using MakeTransparent but decided to accept Phil Wright's answer because it's more general and got the most votes.
leod
+3  A: 

One good approach is to use the ImageAttributes class to setup a list of colors to remap when drawing takes place. The advantage of this is good performance as well as allowing you to alter the remapping colors very easily. Try something like this code...

ImageAttributes attribs = new ImageAttributes();
List<ColorMap> colorMaps = new List<ColorMap>();
//
// Remap black top be transparent
ColorMap remap = new ColorMap();
remap.OldColor = Color.Black;
remap.NewColor = Color.Transparent;
colorMaps.Add(remap);
//
// ...add additional remapping entries here...
//
attribs.SetRemapTable(colorMaps.ToArray(), ColorAdjustType.Bitmap);
context.Graphics.DrawImage(image, imageRect, 0, 0, 
                           imageRect.Width, imageRect.Height, 
                           GraphicsUnit.Pixel, attribs);
Phil Wright