Image img = new Image();//实例化Image控件
img.Source = BitmapFilter(bitmap,0xff,0xff,0xff);//加载图像,bitmap是BitmapSource对象是图片数据,R=0xff,G=0xff,B=0xff代表的是白色,去掉白色背景
//img.Source = BitmapFilter(bitmap,0xff,0xff,0xff,0xff);//加载图像,bitmap是BitmapSource对象是图片数据,R=0xff,G=0xff,B=0xff,Alpha = 0xff (这个是透明度)代表的是白色,去掉白色背景
/// <summary>
/// 图片颜色过滤,去除指定的RBG值
/// </summary>
/// <param name="bitmap"></param>
/// <param name="R"></param>
/// <param name="G"></param>
/// <param name="B"></param>
/// <param name="Alpha"></param>
/// <returns></returns>
private BitmapSource BitmapFilter(BitmapSource bitmap, Int32 R, Int32 G, Int32 B, Int32 Alpha = 0xff)
{
FormatConvertedBitmap fb = new FormatConvertedBitmap();//图片像素格式转换类
fb.BeginInit();
fb.Source = bitmap;
fb.EndInit();
var stride = (bitmap.PixelWidth * bitmap.Format.BitsPerPixel + 7) / 8;
byte[] buf = new byte[fb.PixelHeight * stride];
fb.CopyPixels(Int32Rect.Empty, buf, stride, 0);
for (long ic = 0; ic < buf.LongLength; ic += 4)
{
if (buf[ic] == R && buf[ic + 1] == G && buf[ic + 2] == B && buf[ic + 3] == Alpha)
{
buf[ic] = 0x00;
buf[ic + 1] = 0x00;
buf[ic + 2] = 0x00;
buf[ic + 3] = 0x00;//透明处理
}
}
return BitmapSource.Create(fb.PixelWidth, fb.PixelHeight, fb.DpiX, fb.DpiY, fb.Format, null, buf, stride);
}
效果图:
去掉白色之前的图片
去掉白色之后的图片,小弟图片没选好,所以看起来是这样
第一次写,写的不好莫骂。