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 bitmapDim bmp As New Bitmap("c:winntcoffee bean.bmp")' get its sizeDim width As Integer = bmp.WidthDim height As Integer = bmp.Height' lock its bits, get a BitmapData object' notice that you must know the bitmap formatDim rect As New Rectangle(0, 0, width, height)Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(Nothing, _    Drawing.Imaging.ImageLockMode.ReadWrite, _    Drawing.Imaging.PixelFormat.Format8bppIndexed)' get the address of its first scan lineDim 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 formatsDim bytes As Integer = width * heightDim pixels(bytes - 1) As Byte' copy the pixels into the arrayMarshal.Copy(ptr, pixels, 0, bytes)' process all the pixels in the array to create a pixelation effectDim r, c As IntegerFor 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    NextNext' copy the pixels back to the bitmapMarshal.Copy(pixels, 0, ptr, bytes)' unlock the bitsbmp.UnlockBits(bmpData)' save the bitmap to another filebmp.Save("c:
ewbitmap.bmp")

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: