Beispiel #1
0
        /// <summary>
        /// 图片黑白处理
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Bitmap GrayImage(Bitmap bmp, int type)
        {
            int    height = bmp.Height;
            int    width  = bmp.Width;
            Bitmap newbmp = new Bitmap(width, height);

            LockBitmap lbmp    = new LockBitmap(bmp);
            LockBitmap newlbmp = new LockBitmap(newbmp);

            lbmp.LockBits();
            newlbmp.LockBits();

            Color pixel;

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    pixel = lbmp.GetPixel(x, y);
                    int r, g, b, Result = 0;
                    r = pixel.R;
                    g = pixel.G;
                    b = pixel.B;
                    switch (type)
                    {
                    case 0:    //平均值法
                        Result = ((r + g + b) / 3);
                        break;

                    case 1:    //最大值法
                        Result = r > g ? r : g;
                        Result = Result > b ? Result : b;
                        break;

                    case 2:    //加权平均值法
                        Result = ((int)(0.3 * r) + (int)(0.59 * g) + (int)(0.11 * b));
                        break;
                    }
                    newlbmp.SetPixel(x, y, Color.FromArgb(Result, Result, Result));
                }
            }
            lbmp.UnlockBits();
            newlbmp.UnlockBits();
            return(newbmp);
        }