日期:2014-05-18  浏览次数:20786 次

C#图片转换为 灰度位图
如何将普通的图片转换为灰度位图呢?在网上搜过些例子 但是转换后图像都变了!

------解决方案--------------------
这个嘛,自己可以写个方法的,但是,在C#里面处理图片,建议在unsafe下面用指针,这样的话,运行的速度很快,否则,你处理大点的图片,你会很纠结的,当然,要先你的项目里面,设置,允许不安全代码...
C# code

//打开图片,并保存为位图
Bitmap thismap= (Bitmap)Image.FromFile("你的图片文件名");

Rectangle rect = new Rectangle(0, 0, thisMap.Width, thisMap.Height);
                BitmapData bmpData = thisMap.LockBits(rect, ImageLockMode.ReadWrite, thisMap.PixelFormat);
                byte temp = 0;
                unsafe
                {
                    //运用指针来处理图片
                    byte* ptr = (byte*)(bmpData.Scan0);
                    for (int i = 0; i < bmpData.Height; i++)
                    {
                        for (int j = 0; j < bmpData.Width; j++)
                        {
                            temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]);//灰度化公式,方法大致有三种,这里用的是加权平均法
                            ptr[0] = ptr[1] = ptr[2] = temp;
                            ptr += 4;//这里的4,是指每个像素的字节数
                        }
                        ptr += bmpData.Stride - bmpData.Width * 4;//偏移量
                    }
                }
                thisMap.UnlockBits(bmpData);
                pictruebox1.Image=this.Map;//显示处理后的灰度图

------解决方案--------------------
一直在用的一个方法:
C# code

        public static Image MakeGrayscale(Image image)
        {
            // source: http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale

            //create a blank bitmap the same size as original
            Bitmap newBitmap = new Bitmap(image.Width, image.Height);

            //get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);

            //create the grayscale ColorMatrix
            ColorMatrix colorMatrix = new ColorMatrix(
               new float[][] 
                  {
                     new float[] {.3f, .3f, .3f, 0, 0},
                     new float[] {.59f, .59f, .59f, 0, 0},
                     new float[] {.11f, .11f, .11f, 0, 0},
                     new float[] {0, 0, 0, 1, 0},
                     new float[] {0, 0, 0, 0, 1}
                  });

            //create some image attributes
            ImageAttributes attributes = new ImageAttributes();

            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            //draw the original image on the new image
            //using the grayscale color matrix
            g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
               0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);

            //dispose the Graphics object
            g.Dispose();
            attributes.Dispose();

            return newBitmap;
        }