■■■

2016年4月3日日曜日

PictureBoxの画像の明るさを変更する方法

PictureBoxの画像の明るさを変更する方法
VB.NET
Public Shared Function AdjustBrightness(ByVal img As Image, _
        ByVal brightness As Integer) As Image
    Dim newImg As New Bitmap(img.Width, img.Height)
    Dim g As Graphics = Graphics.FromImage(newImg)

    Dim plusVal As Single = CSng(brightness) / 255.0F
    Dim cm As New System.Drawing.Imaging.ColorMatrix(New Single()() _
        {New Single() {1, 0, 0, 0, 0}, _
         New Single() {0, 1, 0, 0, 0}, _
         New Single() {0, 0, 1, 0, 0}, _
         New Single() {0, 0, 0, 1, 0}, _
         New Single() {plusVal, plusVal, plusVal, 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 AdjustBrightness(Image img, int brightness)
{
    Bitmap newImg = new Bitmap(img.Width, img.Height);
    Graphics g = Graphics.FromImage(newImg);

    float plusVal = (float)brightness / 255f;
    System.Drawing.Imaging.ColorMatrix cm =
        new System.Drawing.Imaging.ColorMatrix(
            new float[][] {
        new float[] {1, 0, 0, 0, 0},
        new float[] {0, 1, 0, 0, 0},
        new float[] {0, 0, 1, 0, 0}, 
        new float[] {0, 0, 0, 1, 0},
        new float[] {plusVal, plusVal, plusVal, 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;
}
■■■