Sprache: VB
Diese Funktion macht aus einem Bild mithilfe einer neuen ColorMatrix ein Schwarz/Weißes Bild (Graustufen) und gibt dieses als neue Kopie zurück
Public Function GrayScale(ByVal Image As Image) As Image
Dim ImgAttr As New Imaging.ImageAttributes()
'Standard-ColorMatrix für Graustufen
Dim ColorMatrix As New Imaging.ColorMatrix(New Single()() {New Single() {0.299, 0.299, 0.299, 0, 0}, New Single() {0.587, 0.587, 0.587, 0, 0}, New Single() {0.114, 0.114, 0.114, 0, 0},New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
'ColorMatrix an ImageAttribute-Objekt übergeben
ImgAttr.SetColorMatrix(ColorMatrix)
'Neue 32bit Bitmap erstellen
Dim NewBitmap = New Bitmap(Image.Width, Image.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
'Resolution (DPI) vom Quellbitmap auf Zielbitmap übertragen
NewBitmap.SetResolution(Image.HorizontalResolution, Image.VerticalResolution)
'Graphicsobjekt von NewBitmap erstellen
Dim NewGraphics As Graphics = Graphics.FromImage(NewBitmap)
'NewBitmap auf NewGraphics zeichnen
NewGraphics.DrawImage(Image, New Rectangle(0, 0, NewBitmap.Width, NewBitmap.Height), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, ImgAttr)
'Ressource freigeben
NewGraphics.Dispose()
ImgAttr.Dispose()
Return NewBitmap
End Function
Public Function GrayScale(ByVal Image As Image) As Image
Dim ImgAttr As New Imaging.ImageAttributes()
'Standard-ColorMatrix für Graustufen
Dim ColorMatrix As New Imaging.ColorMatrix(New Single()() {New Single() {0.299, 0.299, 0.299, 0, 0}, New Single() {0.587, 0.587, 0.587, 0, 0}, New Single() {0.114, 0.114, 0.114, 0, 0},New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
'ColorMatrix an ImageAttribute-Objekt übergeben
ImgAttr.SetColorMatrix(ColorMatrix)
'Neue 32bit Bitmap erstellen
Dim NewBitmap = New Bitmap(Image.Width, Image.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
'Resolution (DPI) vom Quellbitmap auf Zielbitmap übertragen
NewBitmap.SetResolution(Image.HorizontalResolution, Image.VerticalResolution)
'Graphicsobjekt von NewBitmap erstellen
Dim NewGraphics As Graphics = Graphics.FromImage(NewBitmap)
'NewBitmap auf NewGraphics zeichnen
NewGraphics.DrawImage(Image, New Rectangle(0, 0, NewBitmap.Width, NewBitmap.Height), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, ImgAttr)
'Ressource freigeben
NewGraphics.Dispose()
ImgAttr.Dispose()
Return NewBitmap
End Function
Alte URL:
/snippet/bild-in-graustufen-umwandeln/170