11 Sept 2012

C#彩色图像转灰度图

C#彩色图像转灰度图,picturebox加载一副图片(本地或者网络图片均可):pic.Load(URL)
使用下面的代码转为灰度图:
private void btnRec_Click(object sender, EventArgs e)
{
Bitmap picImage = (Bitmap)pic.Image.Clone();
int rows = picImage.Height;
int cols = picImage.Width;
Rectangle rect = new Rectangle(0, 0, cols, rows);
BitmapData picData = picImage.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
byte temp = 0;
unsafe
{
byte* ptr = (byte*)(picData.Scan0);
for (int i = 0; i < rows; i++ )
{
for (int j = 0; j < cols; j++ )
{
temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]); // get gray value
ptr[0] = ptr[1] = ptr[2] = temp; // set current pixel
ptr += 3; // point to next pixel
}
ptr += picData.Stride - picData.Width * 3; // row data offset
}
} // end of unsafe code
picImage.UnlockBits(picData);

//pic.Image = picImage;
}

No comments :

Post a Comment