One can decrease the time it takes to process a bitmap image in C# by manually accessing the image’s raw data as opposed to using the default GetPixel and SetPixel functions.

C-Sharp comes with many built-in image processing functions. Built on top of GDI, GDI-Plus is a powerful tool. However GDI+ has its limitations. For example, many of you have realized by now that bitmap image scanning in Csharp is extremely slow.

The reason it’s so slow is due to the GetPixel and SetPixel functions. Each time one of these functions is called, the bitmap image is locked, the bytes are accessed/modified, and the bitmap is unlocked. The repetitive locking-unlocking routine is what makes writing to an image in C#.Net so slow.

The answer is to manually lock the bitmap, access and/or modify the bits, and finally release the image. That way each write and read operation doesn’t have to lock and unlock the entire picture. You might be stunned how much this can increase the speed your picture processing functions.

Here is the C# source code to lock a bitmap:

Rectangle bounds = new Rectangle(Point.Empty, bitmap.Size);

Int width = (int)(bounds.Width * sizeof(PixelData));

BitmapData bitmapData = bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

Byte* pBase = (Byte*)bitmapData.Scan0.ToPointer();

Where PixelData is a structure with a variable for each of the argb values of a color.

To access a pixel use the code below:

PixelData* pixelData = (PixelData*)(pBase + y * width + x * sizeof(PixelData));

Don’t forget when you are done to unlock the picture:


Leave a Reply

Your email address will not be published. Required fields are marked *