c#将图片转为灰度图片

public static Image ConvertToGrayScale(Image orginalImage)
{
    Bitmap newImage = new Bitmap(orginalImage);
    BitmapData orginalData = (orginalImage as Bitmap).LockBits(new Rectangle(0, 0, orginalImage.Width, orginalImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

    BitmapData newData = (newImage as Bitmap).LockBits(new Rectangle(0, 0, orginalImage.Width, orginalImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    int orginalstride = orginalData.Stride;
    System.IntPtr orginalScan0 = orginalData.Scan0;

    int newstride = newData.Stride;
    System.IntPtr newScan0 = newData.Scan0;
    unsafe
    {
        byte* pOrginal = (byte*)(void*)orginalScan0;
        byte* pNew = (byte*)(void*)newScan0;

        int nOffset = orginalstride - orginalImage.Width * 3;

        byte red, green, blue;

        for (int y = 0; y < orginalImage.Height; ++y)
        {
            for (int x = 0; x < orginalImage.Width; ++x)
            {
                blue = pOrginal[0];
                green = pOrginal[1];
                red = pOrginal[2];

                byte newPixel = Convert.ToByte((blue + red + green) / 3);

                pNew[0] = newPixel;
                pNew[1] = newPixel;
                pNew[2] = newPixel;

                pOrginal += 3;
                pNew += 3;
            }
            pOrginal += nOffset;
            pNew += nOffset;
        }
    }
    (orginalImage as Bitmap).UnlockBits(orginalData);
    (newImage as Bitmap).UnlockBits(newData);
    return newImage;
}
 转自:  http://outofmemory.cn/code-snippet/584/c-jiang-tupian-zhuanwei-huidu-tupian

你可能感兴趣的:(C#)