■■■

2016年4月3日日曜日

PictureBoxの色を反転させる方法

PictureBoxの色を反転させる方法
VB.NET
Public Shared Function CreateNegativeImage(ByVal img As Image) As Image

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

    Dim g As Graphics = Graphics.FromImage(negaImg)

    Dim cm As New System.Drawing.Imaging.ColorMatrix()

    cm.Matrix00 = -1
    cm.Matrix11 = -1
    cm.Matrix22 = -1
    cm.Matrix33 = 1
    cm.Matrix40 = 1
    cm.Matrix41 = 1
    cm.Matrix42 = 1
    cm.Matrix44 = 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 negaImg
End Function

C#
public static Image CreateNegativeImage(Image img)
{
    Bitmap negaImg = new Bitmap(img.Width, img.Height);

    Graphics g = Graphics.FromImage(negaImg);

    System.Drawing.Imaging.ColorMatrix cm =
        new System.Drawing.Imaging.ColorMatrix();

    cm.Matrix00 = -1;
    cm.Matrix11 = -1;
    cm.Matrix22 = -1;
    cm.Matrix33 = 1;
    cm.Matrix40 = cm.Matrix41 = cm.Matrix42 = cm.Matrix44 = 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 negaImg;
}



■■■