我有一个 System.Drawing.Image 类型的对象,并希望使每个具有某种特定颜色的像素(例如黑色)透明(即,将此像素的 alpha 设置为 0)。
做这个的最好方式是什么?
我有一个 System.Drawing.Image 类型的对象,并希望使每个具有某种特定颜色的像素(例如黑色)透明(即,将此像素的 alpha 设置为 0)。
做这个的最好方式是什么?
一种好的方法是使用ImageAttributes类来设置颜色列表,以便在绘制时重新映射。这样做的好处是良好的性能以及允许您非常轻松地更改重新映射颜色。试试这样的代码......
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);
从图像构造一个位图,然后在该位图上调用 MakeTransparent()。它允许您指定应该呈现为透明的颜色。
你只知道它是一个图像吗?如果它是位图,您可以调用 LockBits,检查/修复每个像素,然后再次解锁这些位。