您的位置:首页 > 其它

彩色图片转换为灰度图(方法)

2010-03-26 15:46 417 查看
private class Consts
{
// 根据 NTSC (North America Television Standards Committee)
// 规定,红绿蓝值分别为 0.299, 0.587, 0.114时为灰度图
public const float GrayRed = 0.3086f;
public const float GrayGreen = 0.6094f;
public const float GrayBlue = 0.082f;
}

/// <summary>
/// 转换彩色图片为灰度图
/// </summary>
/// <param name="image"></param>
public static void ConvertToGrayscale(Image image)
{
DrawImage(image, GetGrayscaleMatrix());
}

/// <summary>
/// 设置转换矩阵
/// </summary>
/// <returns></returns>
public static float[][] GetGrayscaleMatrix()
{
// Set the luminosity of the colors using grayscale weighting
float[][] matrix = {
new float[] {Consts.GrayRed, Consts.GrayRed, Consts.GrayRed, 0, 0},
new float[] {Consts.GrayGreen, Consts.GrayGreen, Consts.GrayGreen, 0, 0},
new float[] {Consts.GrayBlue, Consts.GrayBlue, Consts.GrayBlue, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}};
return matrix;
}

/// <summary>
/// 用指定的矩形画图
/// </summary>
/// <param name="image"></param>
/// <param name="matrix"></param>
private static void DrawImage(Image image, float[][] matrix)
{
// Setup the attributes class
ColorMatrix cm = new ColorMatrix(matrix);
ImageAttributes attr = new ImageAttributes();

try
{
// Draw the image
attr.SetColorMatrix(cm);
DrawImage(image, attr);
}
finally
{
attr.Dispose();
}
}

/// <summary>
/// 用指定的属性画图
/// </summary>
/// <param name="image"></param>
/// <param name="attr"></param>
private static void DrawImage(Image image, ImageAttributes attr)
{
Graphics g = Graphics.FromImage(image);
try
{
Rectangle destRect = new Rectangle(0, 0, image.Width, image.Height);
g.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attr);
}
finally
{
g.Dispose();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: