aStore Best Buy

Monday, January 19, 2009

Speed Up C# Bitmap Image Processing

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 extremly 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:


bitmap.UnlockBits(bitmapData);

For an example C# application demonstrating the difference between traditional GDI+ and unsafe image processing visit => http://vckicks.110mb.com/fast-image-processing.html

If you liked this CSharp article, check out Visual C# Kicks for more useful C# source code => http://vckicks.110mb.com

Buy Canon SX110
Canon HF100 Best Deals
A590 Canon on Sale

No comments:

Post a Comment

Nikon D90 Review

iPod Touch Sales

HDTV Guide

GPS Store

Tool Reviews

aStore Best Buy

Welcome to aStore Best Buy