/// <summary>
/// 灰度图像处理
/// </summary>
public class PicGray
{/// <summary>/// 获取pic图像对应的黑白图像/// </summary>/// <param name="pic"></param>/// <param name="NumGray">像素灰度值</param>/// <returns></returns>public static Bitmap ToBlack(Bitmap pic, int NumGray = 220){// 灰度图像转化为黑白图像if (isGrayPic(pic)){Color Black = Color.FromArgb(255, 0, 0, 1);Color White = Color.FromArgb(255, 255, 255, 254);Bitmap tmp = new Bitmap(pic.Width, pic.Height);for (int h = 0; h < pic.Height; h++){for (int w = 0; w < pic.Width; w++){Color C = pic.GetPixel(w, h);Color D = (C.R < NumGray && C.G < NumGray && C.B < NumGray) ? Black : White;tmp.SetPixel(w, h, D);}}return tmp;}else return pic;}/// <summary>/// 判断图像是否为灰度图像/// </summary>/// <param name="pic"></param>/// <returns></returns>public static bool isGrayPic(Bitmap pic){int stepH = pic.Height / 100;int stepW = pic.Width / 100;if (stepH < 1) stepH = 1;if (stepW < 1) stepW = 1;for (int h = 0; h < pic.Height; h = h + stepH){for (int w = 0; w < pic.Width; w = w + stepW){Color C = pic.GetPixel(w, h);if (C.R != C.G || C.G != C.B) return false;}}return true;}/// <summary>/// 转化为一位位深度的图像(仅保留黑色)/// </summary>/// <param name="pic"></param>/// <returns></returns>private Bitmap To1Bit(Bitmap pic){var newbitmap = pic.Clone(new Rectangle(0, 0, pic.Width, pic.Height), PixelFormat.Format1bppIndexed);return newbitmap;}}