Saturday, 28 March 2009

Speeding up GetPixel with Unsafe Code, Part II

In relation to my previous article on replacing GetPixel, I didn't include an example of how to replace SetPixel. So if you haven't figured it out, here's an example that will colour every pixel in a bitmap red, which should point you in the right direction.

private static void SetPixelExample(ref Bitmap bitmap)
{
int CurScanLine = 0;
Rectangle Rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData TempBitmapData =
bitmap.LockBits(Rect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

while (CurScanLine < bitmap.Height)
{
for (int x = 0; x < bitmap.Width; x++)
{
SetPixelNew(ref TempBitmapData, x, CurScanLine, Color.Red);
}
CurScanLine++;
}

bitmap.UnlockBits(TempBitmapData);
}

private static unsafe void SetPixelNew(ref BitmapData bitmapData, int x, int y, Color colour)
{
byte* PixelPointer = null; // Pointer to our pixel data
int ColourPlanes = 3;
PixelPointer = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
PixelPointer[ColourPlanes * x] = colour.B;
PixelPointer[(ColourPlanes * x) + 1] = colour.G;
PixelPointer[(ColourPlanes * x) + 2] = colour.R;
}

I've used a similar technique to write a speedy PCX image file decoder which decodes the PCX file, places it in a byte array then writes the colour data to a bitmap, which is one possible application to consider.

Labels:

Bookmark and Share

0 Comments:

Post a Comment



<< Home