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

元画像

セピア画像