|
|
Title | Convert an image to GrayScale one pixel at a time in VB .NET |
Keywords | grayscale, pixel-by-pixel, VB.NET |
Categories | Graphics, VB.NET |
|
|
For each pixel in the image, calculate a weighted average of the pixel's red, green, and blue components. Set all three components to that value.
|
|
' Convert each pixel to grayscale.
Private Sub btnGrayscale_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnGrayscale.Click
Dim clr As Integer
Dim xmax As Integer
Dim ymax As Integer
Dim x As Integer
Dim y As Integer
' Get the bitmap and its dimensions.
Dim bm As Bitmap = picImage.Image
xmax = bm.Width - 1
ymax = bm.Height - 1
' Convert the pixels to grayscale.
For y = 0 To ymax
For x = 0 To xmax
' Convert this pixel.
With bm.GetPixel(x, y)
clr = 0.3 * .R + 0.5 * .G + 0.2 * .B
End With
bm.SetPixel(x, y, _
Color.FromArgb(255, clr, clr, clr))
Next x
Next y
' Display the results.
picImage.Image = bm
End Sub
|
|
Note that simply averaging the pixel's components produces a reasonably good result.
|
|
|
|
|
|