Fast image processing in c#

While the Bitmap provide GetPixel() and SetPixel() for accessing individual pixels in the bitmap - It is too slow and therefore it not suitable to image processing. The following FastBitmap class allows us to fastly access the raw memory of bitmap data via pointers.

About FastBitmap

The FastBitmap implement the IDisposable Interface. The constructor takes the bitmap we want to process and an optional rectangle of the bitmap we want to access. It will locks the raw memory of bitmap and will allow us to access the raw memory. The Dispose method should be called to unlock the memory and free the unmanaged resources when we done with processing the bitmap.

The class provides some properties which allows to locate individual pixels in the bitmap

  • PixelSize holds the size of pixel in bytes
  • Stride holds the width in bytes of row of pixels of the image
  • Scan0 holds a pointer to the location of the left top pixel of the rectangle we want to process.
  • XX,YY are the left and top of the rectangle of the bitmap we want to process.
  • Width,Height are the width and height of the rectangle of the bitmap we want to process.

For example:

FastBitmap Sample
 fb = new FastBitmap(bitmap,3,1,4,3);
 ...
 fb.Dispose()

Suppose the bitmap is color image in 24bpp-BGR:

  • The bitmap dimensions are 9x6
  • fb.PixelSize is 3 ( Each pixel has 3 bytes)
  • The fb.Stride is PixelSize * bitmap's width = 3 * 9 = 27
  • The rectangle we want to processed is located at (3,1)
    • fb.XX = 3
    • fb.YY = 1
  • The dimensions of the rectangle we want to processed is 4x3
    • fb.Width = 4
    • fb.Height= 3
  • The fb.scan0 will point to pixel located at (3,1).

Using those values we can access the pixel (xx,yy) in the rectangle by the following calculation:


fb.Scan0 + yy * fb.Stride + xx * fb.PixelSize