C#中級 コーディング例
G7)画像グレー化
画像(ビットマップ)をグレー化加工して、返します。
//source:対象ビットマップ画像
public static Bitmap ToGray(Bitmap source)
{
Bitmap outputBmp = new Bitmap(source.Width, source.Height);
//グレー用のカラーマトリックス
//グレーは以下の式で RGB を変換します:
//R' = 0.299R + 0.299G + 0.299B
//G' = 0.587R + 0.587G + 0.587B
//B' = 0.114R + 0.114G + 0.114B
//ColorMatrix はこれをそのまま行列化したものです。
float[][] matrix = {
new float[] {0.299f, 0.299f, 0.299f, 0, 0},
new float[] {0.587f, 0.587f, 0.587f, 0, 0},
new float[] {0.114f, 0.114f, 0.114f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
};
//ImageAttributes オブジェクトを、Graphics オブジェクトの DrawImage メソッドに渡します
ColorMatrix cm = new ColorMatrix(matrix);
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm);
using (Graphics g = Graphics.FromImage(outputBmp))
{
g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height),
0, 0, source.Width, source.Height, GraphicsUnit.Pixel, ia);
}
return outputBmp;
}

元画像

グレー画像