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
 
 
 
 
TitleUse the GetDIBits and SetDIBits API functions to convert a picture to gray scale
DescriptionThis example shows how to use the GetDIBits and SetDIBits API functions to convert a picture to gray scale in Visual Basic 6.
KeywordsGetDIBits, SetDIBits, gray scale, picture
CategoriesGraphics, API
 
The MakeGray subroutine prepares some data structures and then uses the GetDIBits API function to get the picture's bitmap data. It chnges each picel's red, green, and blue components to the average of those three values. It then uses SetDIBits to save the changes into the PictureBox.
 
' Convert a color image to gray scale.
Private Sub MakeGray(ByVal picColor As PictureBox)
Dim bitmap_info As BITMAPINFO
Dim pixels() As Byte
Dim bytes_per_scanLine As Integer
Dim pad_per_scanLine As Integer
Dim X As Integer
Dim Y As Integer
Dim ave_color As Byte

    ' Prepare the bitmap description.
    With bitmap_info.bmiHeader
        .biSize = 40
        .biWidth = picColor.ScaleWidth
        ' Use negative height to scan top-down.
        .biHeight = -picColor.ScaleHeight
        .biPlanes = 1
        .biBitCount = 32
        .biCompression = BI_RGB
        bytes_per_scanLine = ((((.biWidth * .biBitCount) + _
            31) \ 32) * 4)
        pad_per_scanLine = bytes_per_scanLine - (((.biWidth _
            * .biBitCount) + 7) \ 8)
        .biSizeImage = bytes_per_scanLine * Abs(.biHeight)
    End With

    ' Load the bitmap's data.
    ReDim pixels(1 To 4, 1 To picColor.ScaleWidth, 1 To _
        picColor.ScaleHeight)
    GetDIBits picColor.hdc, picColor.Image, _
        0, picColor.ScaleHeight, pixels(1, 1, 1), _
        bitmap_info, DIB_RGB_COLORS

    ' Modify the pixels.
    For Y = 1 To picColor.ScaleHeight
        For X = 1 To picColor.ScaleWidth
            ave_color = CByte((CInt(pixels(pixR, X, Y)) + _
                pixels(pixG, X, Y) + _
                pixels(pixB, X, Y)) \ 3)
            pixels(pixR, X, Y) = ave_color
            pixels(pixG, X, Y) = ave_color
            pixels(pixB, X, Y) = ave_color
        Next X
    Next Y

    ' Display the result.
    SetDIBits picColor.hdc, picColor.Image, _
        0, picColor.ScaleHeight, pixels(1, 1, 1), _
        bitmap_info, DIB_RGB_COLORS
    picColor.Picture = picColor.Image
End Sub
 
My book Visual Basic Graphics Programming has a lot more information about graphics.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated