Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleConvert an image to GrayScale one pixel at a time in VB .NET
Keywordsgrayscale, pixel-by-pixel, VB.NET
CategoriesGraphics, 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.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated