c# 彩色图片变为黑白图片

来源:互联网 发布:苹果手机壁纸软件排行 编辑:程序博客网 时间:2024/04/30 15:37
               //// <summary>
/// 变成黑白图
/// </summary>
/// <param name="bmp">原始图</param>
/// <param name="mode">模式。0:加权平均  1:算数平均</param>
/// <returns></returns>
private Bitmap ToGray(Bitmap bmp,int mode)
{
if (bmp == null)

{
return null;
}


int w = bmp.Width;
int h = bmp.Height;
try

{
byte newColor = 0;
BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
 
{
byte* p = (byte*)srcData.Scan0.ToPointer();
for (int y = 0; y < h; y++)

{
for (int x = 0; x < w; x++)

{


if (mode == 0) //加权平均

{
newColor = (byte)((float)p[0] * 0.114f + (float)p[1] * 0.587f + (float)p[2] * 0.299f);
}
else    // 算数平均

{
newColor = (byte)((float)(p[0] + p[1] + p[2]) / 3.0f);
}
p[0] = newColor;
p[1] = newColor;
p[2] = newColor;


p += 3;
}
p += srcData.Stride - w * 3;
}
bmp.UnlockBits(srcData);
return bmp;
}
}
catch

{
return null;
}


}






调用:
pictureBox2.Image=(System.Drawing.Image)ToGray((System.Drawing.Bitmap)pictureBox1.Image,0);
0 0