C#中級 コーディング例
G10)画像コントラスト補正
画像をコントラスト補正して、ビットマップで返します。弱く・元・強く
//source:対象イメージ画像
public static Bitmap AdjustContrast(Image source, float contrast)
{
// contrast: 0.0f = グレー, 1.0f = 元のコントラスト, 2.0f = 2倍
float t = 0.5f * (1.0f - contrast);
//ColorMatrix はこれをそのまま行列化したものです
float[][] matrix = {
new float[] { contrast, 0, 0, 0, 0 },
new float[] { 0, contrast, 0, 0, 0 },
new float[] { 0, 0, contrast, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { t, t, t, 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 g = Graphics.FromImage(outputBmp))
{
g.DrawImage(source,
new Rectangle(0, 0, outputBmp.Width, outputBmp.Height),
0, 0, source.Width, source.Height,
GraphicsUnit.Pixel,
attributes);
}
return outputBmp;
}
元画像
弱い 強い