C# Programming > Drawing GDI+

Fast Image Processing
Page 2


Reading and Writing the Image

At this point you have successfully locked the bitmap image. Now you can move on to writing the C# code that will access the raw bytes of the bitmap.

Remember we kept track of certain values in the LockImage()function. You can use those values to write your own GetPixel function to replace the GDI+ one that comes in the .NET Framework:

public Color GetPixel(int x, int y)
    pixelData = (PixelData*)(pBase + y * width + x * sizeof(PixelData));
    return Color.FromArgb(pixelData->alpha, pixelData->red, pixelData->green, pixelData->blue);

Not hard at all, right? Since the image is not locked and unlocked as with the traditional GetPixel function, this version is a lot faster, greating increasing the image processing speed of your applications.

All image processing applications need to also be able to write to a bitmap image quickly. So let's write the SetPixel replacement. The concept is exactly the same, instead of returning a color however, we were going to apply a color to the image:

public void SetPixel(int x, int y, Color color)
    PixelData* data = (PixelData*)(pBase + y * width + x * sizeof(PixelData));
    data->alpha = color.A;
    data->red = color.R;
    data->green = color.G;
    data->blue = color.B;

Unlocking the Bitmap Image

Unlocking the image is the easiest part of all:


Using the Final Code

The final code is really simple to use. The goal of the FastBitmap class was to make it so you could go back and easily insert it into your picture processing C# applications and increase their speed.

So let's pretend you have some existing C# code that looks like this:

Bitmap myBmp = new Bitmap("C:\image.bmp");
Color firstPixel = myBmp.GetPixel(0, 0);

Now let's insert your new FastBitmap class to speed up the image processing speed:

Bitmap myBmp = new Bitmap("C:\image.bmp");
FastBitmap processor = new FastBitmap(myBmp);

Color firstPixel = processor.GetPixel(0, 0);

It might seem a little strange that the source code got bigger when we are trying to improve the speed, but that is only because this is a small example. I recommend you download the example application at the bottom of the page. It comes with the full source code for the FastBitmap class as well as an example C# application that utilizes it...


Page 1
<< Fast Image Processing


Back to C# Article List