■■■

2016年4月3日日曜日

PictureBoxの画像コントラストを変更する方法

PictureBoxの画像コントラストを変更する方法
VB.NET
Public Shared Function AdjustContrast(ByVal img As Image, _
        ByVal contrast As Single) As Image

    Dim newImg As New Bitmap(img.Width, img.Height)

    Dim g As Graphics = Graphics.FromImage(newImg)

    Dim scale As Single = (100.0F + contrast) / 100.0F
    scale *= scale
    Dim append As Single = 0.5F * (1.0F - scale)
    Dim cm As New System.Drawing.Imaging.ColorMatrix(New Single()() _
        {New Single() {scale, 0, 0, 0, 0}, _
         New Single() {0, scale, 0, 0, 0}, _
         New Single() {0, 0, scale, 0, 0}, _
         New Single() {0, 0, 0, 1, 0}, _
         New Single() {append, append, append, 0, 1}})

    Dim ia As New System.Drawing.Imaging.ImageAttributes()

    ia.SetColorMatrix(cm)


    g.DrawImage(img, New Rectangle(0, 0, img.Width, img.Height), _
                0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia)

    g.Dispose()

    Return newImg
End Function
C#
public static Image AdjustContrast(Image img, float contrast)
{

    Bitmap newImg = new Bitmap(img.Width, img.Height);
    Graphics g = Graphics.FromImage(newImg);

    float scale = (100f + contrast) / 100f;
    scale *= scale;
    float append = 0.5f * (1f - scale);
    System.Drawing.Imaging.ColorMatrix cm =
        new System.Drawing.Imaging.ColorMatrix(
            new float[][] {
        new float[] {scale, 0, 0, 0, 0},
        new float[] {0, scale, 0, 0, 0},
        new float[] {0, 0, scale, 0, 0}, 
        new float[] {0, 0, 0, 1, 0},
        new float[] {append, append, append, 0, 1}
    });

    System.Drawing.Imaging.ImageAttributes ia =
        new System.Drawing.Imaging.ImageAttributes();

    ia.SetColorMatrix(cm);

    g.DrawImage(img,
        new Rectangle(0, 0, img.Width, img.Height),
        0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia);

    g.Dispose();

    return newImg;
}

■■■