使具有特定颜色的图像的每个像素透明
时间:2020-03-06 15:01:23 来源:igfitidea点击:
我有一个类型为System.Drawing.Image的对象,并希望使每个具有某种特定颜色的像素(例如黑色)透明(即,将该像素的alpha设置为0)。
做这个的最好方式是什么?
解决方案
我们只知道这是一张图片吗?如果是位图,则可以调用LockBits,检查/修复每个像素,然后再次解锁位。
从图像构造一个位图,然后在该位图上调用MakeTransparent()。它允许我们指定应呈现为透明的颜色。
一种好的方法是使用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);