6

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?

leod
  • 83
  • 2
  • 7
  • i have a very similar question and i was wondering if you could help me: http://stackoverflow.com/questions/1096165/transparent-winform-using-selective-colors – Alex Gordon Jul 08 '09 at 05:28

3 Answers3

6

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
  • 22,580
  • 14
  • 83
  • 137
3

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
  • 5,392
  • 30
  • 39
  • 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 Oct 02 '08 at 12:49
  • 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 Nov 01 '08 at 19:25
2

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194