日期:2014-05-18 浏览次数:20849 次
//打开图片,并保存为位图 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;//显示处理后的灰度图
------解决方案--------------------
一直在用的一个方法:
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; }