使具有特定颜色的图像的每个像素透明

我有一个System.Drawing.Image类型的对象,并希望使每个具有某种特定颜色的像素,例如黑色,透明(即,为此像素将alpha设置为0)。

做这个的最好方式是什么?

一种好的方法是使用ImageAttributes类设置要在绘制时重新映射的颜色列表。 这样做的好处是良好的性能,并允许您非常容易地改变重映射颜色。 试试这样的代码…

ImageAttributes attribs = new ImageAttributes(); List colorMaps = new List(); // // 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); 

从Image构造一个Bitmap,然后在该Bitmap上调用MakeTransparent()。 它允许您指定应呈现为透明的颜色。

你只知道这是一张图片吗? 如果它是一个位图,你可以调用LockBits,检查/修复每个像素,然后再次解锁这些位。