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
 
 
 
 
 
TitleFill a large area one pixel at a time using SetBitmapBits
Keywordsgraphics, SetBitmapBits, GetBitmapBits, pixel
CategoriesGraphics
 
See my book Visual Basic Graphics Programming for more information on graphics in Visual Basic.

Use GetDIBits to load the image's pixel values into a device-independent bitmap (DIB) structure. Modify the pixel values and use SetDIBits to update the image.

Note that this program introduces a small amount of color degredation if you are running with less than 24-bit color depth because GetDIBits and SetDIBits store color values in 3 bytes (essentially 24-bit color) but the system uses fewer bits to store the values.

 
' Prepare the bitmap description.
wid = Picture1.ScaleWidth
hgt = Picture1.ScaleHeight
With bitmap_info.bmiHeader
    .biSize = 40
    .biWidth = wid
    ' Use negative height to scan top-down.
    .biHeight = -hgt
    .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 wid, 1 To hgt)
GetDIBits Picture1.hdc, Picture1.Image, _
    0, hgt, pixels(1, 1, 1), _
    bitmap_info, DIB_RGB_COLORS

' Modify the pixels.
For Y = 1 To hgt
    For X = 1 To wid
        ' Make the pixel black.
        pixels(pixR, X, Y) = 0
        pixels(pixG, X, Y) = 0
        pixels(pixB, X, Y) = 0

        If ((X \ 20) Mod 2) <> ((Y \ 20) Mod 2) Then
            ' Set the pixel color.
            pixels(clr, X, Y) = 255
        End If
    Next X
Next Y

' Display the result.
SetDIBits Picture1.hdc, Picture1.Image, _
    0, hgt, pixels(1, 1, 1), _
    bitmap_info, DIB_RGB_COLORS
Picture1.Picture = Picture1.Image
 
This program, together with the following programs, compares the speeds of different methods for manipulating an image's pixels one at a time.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated