C#中級 コーディング例
G9)画像彩度補正
画像を彩度補正して、ビットマップで返します。薄く・元・鮮やか
//source:対象イメージ画像
public static Bitmap AdjustSaturation(Bitmap source, float saturation)
{
// saturation: 0.0f = 白黒, 1.0f = 元の彩度, 2.0f = 2倍の彩度
float s = saturation;
// NTSC 系の輝度係数
float rw = 0.3086f;
float gw = 0.6094f;
float bw = 0.0820f;
float a = (1 - s) * rw + s;
float b = (1 - s) * rw;
float c = (1 - s) * rw;
float d = (1 - s) * gw;
float e = (1 - s) * gw + s;
float f = (1 - s) * gw;
float g = (1 - s) * bw;
float h = (1 - s) * bw;
float i = (1 - s) * bw + s;
//ColorMatrix はこれをそのまま行列化したものです
float[][] matrix = {
new float[] { a, d, g, 0, 0 },
new float[] { b, e, h, 0, 0 },
new float[] { c, f, i, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 }
};
var colorMatrix = new ColorMatrix(matrix);
var attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix);
//ImageAttributes オブジェクトを、Graphics オブジェクトの DrawImage メソッドに渡します
Bitmap outputBmp = new Bitmap(source.Width, source.Height);
using (Graphics gph = Graphics.FromImage(outputBmp))
{
gph.DrawImage(source,
new Rectangle(0, 0, outputBmp.Width, outputBmp.Height),
0, 0, source.Width, source.Height,
GraphicsUnit.Pixel,
attributes);
}
return outputBmp;
}

元画像
薄い 鮮やか