WPF图片背景色过滤

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);
        }


效果图:

去掉白色之前的图片


去掉白色之后的图片,小弟图片没选好,所以看起来是这样



第一次写,写的不好莫骂。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值