C# Programming > Drawing GDI+

Fast Image Processing

c# image processing

Traditional GDI+ Picture Processing

The .NET Framework comes with a powerful image processing library, GDI+, which builds upon the veteran GDI. While GDI+ is a powerful built-in library, it has its limitations. For example, many of us know by now how slow processing bitmap images in C# can be. However there are ways to make GDI+ image processing faster in C#.

The reason it is so slow is due to the GetPixel and SetPixel functions. Each time you call one of these functions in your C# code, the bitmap image is locked, the bitmap bytes are accessed/modified, and the image is unlocked. The repetitive locking-unlocking part of the code is what makes picture processing in C# so slow.

The Solution - Unsafe Code

The solution is to manually lock the picture, access/modify the bits yourself, and then unlock the bitmap image. That way each read and write of the pixels doesn't have to lock the whole image. You will be suprised how much this can speed up your image processing functions.

To access the bitmap image's raw data we will need unsafe code. The unsafe keyword can be declared at a class or at a single function. Since we are going to make a class that will replace the traditional GetPixel and SetPixel functions, we are going to declared the entire class unsafe like so:

unsafe public class FastBitmap

If you try to compile that right off the bat you are going to get an error. This is because we need to tell the C# project to allow unsafe code:

c# unsafe code

The above page can be found on Project Properties.

Locking the Bitmap

The first step to write fast picture processing C#.NET functions is to lock the bitmap image.

The LockImage() function of our FastBitmap class will need to perform two functions: lock the image with the LockBits built-in call and keep track of values you will need to transverse the image later.

Here is a code snippet of the C# function. (Remember to download the full source code at the end of the article):

Rectangle bounds = new Rectangle(Point.Empty, workingBitmap.Size);
width = (int)(bounds.Width * sizeof(PixelData));
if (width % 4 != 0) width = 4 * (width / 4 + 1);

//Lock Image bitmapData = workingBitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); pBase = (Byte*)bitmapData.Scan0.ToPointer();

The parts to note is that you need the dimensions of the bitmap image and the PixelFormat can be set to also read the transperancy of pixels.

Continue to Page 2 - Unsafe Read/Write

Back to C# Article List