|
|
Title | Manipulate image pixels very quickly using LockBits in VB .NET |
Description | This example shows how to manipulate image pixels very quickly using LockBits in VB .NET. It the Bitmap object's LockBits method to lock its bits and uses Marshal.Copy to copy the pixel data into a managed array. After processing the pixels, it uses Marshal.Copy to copy the pixel data back into the bitmap and then calls the Bitmap object's UnlockBits method. |
Keywords | image, pixel, image processing, unmanaged array, LockBits, VB .NET |
Categories | Graphics, VB.NET |
|
|
The LockBitmap subroutine uses the Bitmap object's LockBits method to lock the object's data. This prevents the data from moving while the program is manipulating it. It allocates an array big enough to hold the pixel data and then calls Marshal.Copy to copy the data from the bitmap into this array.
|
|
Public g_RowSizeBytes As Integer
Public g_PixBytes() As Byte
Private m_BitmapData As BitmapData
' Lock the bitmap's data.
Public Sub LockBitmap(ByVal bm As Bitmap)
' Lock the bitmap data.
Dim bounds As Rectangle = New Rectangle( _
0, 0, bm.Width, bm.Height)
m_BitmapData = bm.LockBits(bounds, _
Imaging.ImageLockMode.ReadWrite, _
Imaging.PixelFormat.Format24bppRgb)
g_RowSizeBytes = m_BitmapData.Stride
' Allocate room for the data.
Dim total_size As Integer = m_BitmapData.Stride * _
m_BitmapData.Height
ReDim g_PixBytes(total_size)
' Copy the data into the g_PixBytes array.
Marshal.Copy(m_BitmapData.Scan0, g_PixBytes, _
0, total_size)
End Sub
|
|
Subroutine UnlockBitmap calls Marshal.Copy to copy the data from the pixel array back into the Bitmap object. It then calls the object's UnlockBits method.
|
|
Public Sub UnlockBitmap(ByVal bm As Bitmap)
' Copy the data back into the bitmap.
Dim total_size As Integer = m_BitmapData.Stride * _
m_BitmapData.Height
Marshal.Copy(g_PixBytes, 0, _
m_BitmapData.Scan0, total_size)
' Unlock the bitmap.
bm.UnlockBits(m_BitmapData)
' Release resources.
g_PixBytes = Nothing
m_BitmapData = Nothing
End Sub
|
|
The main program calls subroutine LockBitmap, modifies the pixel data, and then calls UnlockBitmap.
|
|
' Lock the bitmap data.
LockBitmap(bm)
pix = 0
For Y = 0 To bm.Height - 1
For X = 0 To bm.Width - 1
' Subtract r, g, and b from 255.
For k = 0 To 2
g_PixBytes(pix) = _
BYTE_255 - g_PixBytes(pix)
pix += 1
Next k
Next X
Next Y
' Unlock the bitmap data.
UnlockBitmap(bm)
|
|
On my computer, this approach is about 10 times faster than directly modifying the bitmap's pixels. The code demonstrates that approach also so you can compare the two.
|
|
|
|
|
|