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?
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With