Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Advanced
Jul 27, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Process individual pixels of a bitmap

While you can access individual pixels of a bitmap by means of the GetPixel and SetPixel methods of the Bitmap object, in practice you seldom want to use these methods, as they are simply too slow for most cpu-intensive operations. Fortunately there is a faster way, which consists of moving all the pixels to an array of bytes, process the array, and move its elements back to the bitmap. You have to use the Bitmap.LockBits method to get a BitmapData object, which you later use to retrieve the address of pixels in memory.

This example shows how to create a "pixelation" effect on a 8-bit-per-pixel bitmap. Notice that you must modify this code for other bitmap formats:

' load a bitmap
Dim bmp As New Bitmap("c:\winnt\coffee bean.bmp")
' get its size
Dim width As Integer = bmp.Width
Dim height As Integer = bmp.Height

' lock its bits, get a BitmapData object
' notice that you must know the bitmap format
Dim rect As New Rectangle(0, 0, width, height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(Nothing, _
    Drawing.Imaging.ImageLockMode.ReadWrite, _
' get the address of its first scan line
Dim ptr As IntPtr = bmpData.Scan0

' prepare an array that will receive all the pixels
' this code is specific to a bitmap with 8 bits per pixels
' you must use a different array type for other formats
Dim bytes As Integer = width * height
Dim pixels(bytes - 1) As Byte
' copy the pixels into the array
Marshal.Copy(ptr, pixels, 0, bytes)

' process all the pixels in the array to create a pixelation effect
Dim r, c As Integer
For r = 0 To height - 1 Step 2
    For c = 0 To width - 1 Step 2
        ' get the index of the array element that corresponds to this pixel
        ' notice that arrays are stored column-wise
        Dim index As Integer = c * height + r
        ' this is the color value of this pixel
        Dim colorValue As Byte = pixels(index)
        ' copy it to the 3 pixels to its right and below it
        pixels(index + 1) = colorValue
        pixels(index + height) = colorValue
        pixels(index + height + 1) = colorValue

' copy the pixels back to the bitmap
Marshal.Copy(pixels, 0, ptr, bytes)
' unlock the bits
' save the bitmap to another file
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date