Rubrik: | VB-Versionen: VB.NET | 01.08.07 |
Manchmal ist es notwendig ein Farbbild in Graustufen umzuwandeln. Das Ganze ist auch gar nicht schwer, wie nachfolgender Tipp zeigt. Mit Hilfe der ColorMatrix-Klasse aus dem
.NET Framework werden die Umrechnungsfaktoren der Farbwerte Rot, Grün und Blau festgelegt. Anschließend wird ein ImageAtributes-Objekt erstellt, der die ColorMatrix zugewiesen wird. Beim
Zeichnen des Bildes wird das ImageAttributes-Objekt dann einfach der DrawImage-Methode des Graphics-Objekt übergeben - et voilá: aus einem Farbbild wird ein Graustufenbild.
Public Function DoGrayScale(ByVal oImage As Image) As Image
' Graustufen - ColorMatrix
Dim oMatrix As New Imaging.ColorMatrix(New Single()() { _
New Single() {0.3, 0.3, 0.3, 0, 0}, _
New Single() {0.6, 0.6, 0.6, 0, 0}, _
New Single() {0.1, 0.1, 0.1, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1}})
' ImageAttribute-Objekt mit Graustufen-ColorMatrix erstellen
Dim oAttr As New Imaging.ImageAttributes()
oAttr.SetColorMatrix(oMatrix)
' Neue Bitmap-Objekt erstellen
Dim imgWidth As Integer = oImage.Width
Dim imgHeight As Integer = oImage.Height
Dim oGrayImage As Image = Image.FromHbitmap( _
New Bitmap(imgWidth, imgHeight).GetHbitmap)
' Bild unter Berücksichtigung des ImageAttributes-Objekts
' mit Farb-Konvertierung neu erstellen
Using g As Graphics = Graphics.FromImage(oGrayImage)
g.DrawImage(oImage, New Rectangle(0, 0, imgWidth, imgHeight), _
0, 0, imgWidth, imgHeight, GraphicsUnit.Pixel, oAttr)
End Using
' neues Bild zurückgeben
Return oGrayImage
End Function
Aufrufbeispiel:
In der PictureBox1 soll das Original-Farbbild angezeigt werden, in der PictureBox2 das entsprechende Garustufenbild.
' Original-Farbbild
PictureBox1.Image = Image.FromFile("bild.gif")
' Graustufenbild
PictureBox2.Image = DoGrayScale(PictureBox1.Image)