public static Image RemoveBg(Bitmap img, int dgGrayValue)
{
int width = img.Width;
int height = img.Height;
BitmapData bdata = img.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
PixelFormat.Format32bppRgb); //红绿蓝个八位,其余8位没使用
unsafe
{
byte* ptr = (byte*)bdata.Scan0.ToPointer();
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (ptr[1] > dgGrayValue)//背景点
{
ptr[0] = ptr[1] = ptr[2] = 255;
}
ptr += 4;
}
ptr += bdata.Stride - width * 4;
}
}
#region 内存法
//获取位图中第一个像素数据的地址
//int byteNum = width * height * 4;
////byte[] four = new byte[width *height ];
//byte[] rgbValue = new byte[byteNum];
////把内存中的图像copy到数组
//Marshal.Copy(ptr, rgbValue, 0, byteNum);
//for (int i = 0; i < rgbValue.Length; i += 4)
//{
// if (rgbValue[i] >= dgGrayValue) //是背景点
// {
// rgbValue[i] = rgbValue[i + 1] = rgbValue[i + 2] = 255;
// // four[i/4] = rgbValue[4];
// }
// else
// {
// //不是背景点的做标记,下一阶段处理噪点用**第四个字节默认值都是255**我们标记为 111
// rgbValue[i + 3] = 111;
// }
//}
////将修改好的数据复制到内存
//Marshal.Copy(rgbValue, 0, ptr, byteNum);
#endregion
//从内存中解锁
img.UnlockBits(bdata);
return img;
}