Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making every pixel of an image having a specific color transparent

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?

like image 509
leod Avatar asked Oct 02 '08 12:10

leod


3 Answers

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);
like image 102
Phil Wright Avatar answered Oct 13 '22 07:10

Phil Wright


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.

like image 27
Martin Avatar answered Oct 13 '22 07:10

Martin


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.

like image 32
Jon Skeet Avatar answered Oct 13 '22 07:10

Jon Skeet