Feedback

Invert Colors from Image

Sprache: VB

This function inverts the colors from an image by using a new color matrix
Public Function InvertColors(ByVal Image As Image) As Image
    Dim ImgAttr As New Imaging.ImageAttributes()

    'Default-ColorMatrix for Inverting
    Dim ColorMatrix As New 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() {0, 0, 0, 0, 1}})

    'Apply ColorMatrix to Image
    ImgAttr.SetColorMatrix(ColorMatrix)

    'Create new 32bit Bitmap
    Dim NewBitmap = New Bitmap(Image.Width, Image.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)

    'Set resolution from Sourceimage to Targetimage
    NewBitmap.SetResolution(Image.HorizontalResolution, Image.VerticalResolution)

    'Create Graphicsobject from NewBitmap
    Dim NewGraphics As Graphics = Graphics.FromImage(NewBitmap)

    'Draw NewBitmap on NewGraphics
    NewGraphics.DrawImage(Image, New Rectangle(0, 0, NewBitmap.Width, NewBitmap.Height), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, ImgAttr)

    'Dispose ressources
    NewGraphics.Dispose()
    ImgAttr.Dispose()
    Return NewBitmap
End Function
Public Function InvertColors(ByVal Image As Image) As Image
    Dim ImgAttr As New Imaging.ImageAttributes()

    'Default-ColorMatrix for Inverting
    Dim ColorMatrix As New 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() {0, 0, 0, 0, 1}})

    'Apply ColorMatrix to Image
    ImgAttr.SetColorMatrix(ColorMatrix)

    'Create new 32bit Bitmap
    Dim NewBitmap = New Bitmap(Image.Width, Image.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)

    'Set resolution from Sourceimage to Targetimage
    NewBitmap.SetResolution(Image.HorizontalResolution, Image.VerticalResolution)

    'Create Graphicsobject from NewBitmap
    Dim NewGraphics As Graphics = Graphics.FromImage(NewBitmap)

    'Draw NewBitmap on NewGraphics
    NewGraphics.DrawImage(Image, New Rectangle(0, 0, NewBitmap.Width, NewBitmap.Height), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, ImgAttr)

    'Dispose ressources
    NewGraphics.Dispose()
    ImgAttr.Dispose()
    Return NewBitmap
End Function

1 Kommentar