Extending the PixelBitmapFilter class

Probably one of the most powerful classes in Z-Pixel, the PixelBitmapFilter class provides fast per-pixel image manipulation in an easy-to-derive class. You might be asking "Why not just use the GetPixel and SetPixel methods of the Bitmap class?" If you've actually tried this, you know why. They are really, really slow. Obviously, this is not acceptable for realtime image manipulation. What you might not know is that the Bitmap class also provides fast access to pixel data besides the GetPixel and SetPixel functions. You might have noticed the function LockBits. This function copies the pixel data of the bitmap into a place in memory. You recieve a pointer to the memory location that you can then use to copy the data to a managed array, and then back into the memory location after you've changed it. Finally, you would call UnlockBits to apply the changes to the Bitmap.

But don't worry about that! Z-Pixel does all of that messy stuff for you. All that you have to do is write your own class that derives from the PixelBitmapFilter class and override its ApplyFilterLogic method. You can use the PixelBitmapFilter methods GetPixel and SetPixel (not to be confused with the Bitmap's slow versions of these functions) to change the pixel data around. Let's look at a simple example in VB.NET. This example converts an image to grayscale by averaging the red, green, and blue components and reassigning them all to the average.

Public Class MyPixelBitmapFilter
   Inherits ZPixel.PixelBitmapFilter

   Protected Overrides Sub ApplyFilterLogic()
      For y as Integer = 0 to ImageHeight - 1
         For x as Integer = 0 to ImageWidth -1
            Dim c as Color = GetPixel(x, y)
            Dim newValue as Integer = (CInt(c.R) + CInt(c.G) + CInt(c.B)) / 3
            SetPixel(x, y, Color.FromARGB(c.A, newValue, newValue, newValue))
   End Sub

End Class

That was quite simple, but it provides a very useful image filter for your programs. If you were to try the same thing with the SetPixel and GetPixel methods of the Bitmap class, it would take quite a long time to finish. Using Z-Pixel, it only takes a few milliseconds.

Last edited Sep 24, 2007 at 9:48 PM by zhuman, version 6


No comments yet.