A faster alternative to the very slow GetPixel() and SetPixel() for .Net System.Drawing.Bitmap

Anybody who works with images often have probably come across .Net Bitmaps (System.Drawing.Bitmap) with their staggeringly slow GetPixel() and SetPixel() methods. Now, if you are going to work directly with images then you’re probably in the wrong place if you are using C# and .Net. However, sometimes you may want to do a small amount image analysis or manipulation from within .Net without the pain of having to pull in any other image libraries – but you find that GetPixel() and SetPixel() are just way too slow to use!

Now there is a faster way to access or manipulate the pixel data stored in a .Net Bitmap, that is to lock it (using LockBits()) and then directly access the raw image data in memory – you unlock it when you’re finished. This method is a lot faster than using Get/SetPixel() but is quite complicated to implement and it’s very messy to look at!

To get around this problem, and to avoid littering my code with gibberish I have written a bitmap wrapper class that wraps a bitmap, locks it, and provides it’s own GetPixel() and SetPixel() functions with which the original bitmap’s image data can be accessed. Using this class you can get fast access to a bitmap while using the familiar Get/SetPixel() paradigm – in this way it should act as a fairly easy drop in replacement for accessing the Bitmap objects directly.

The class is called BmpPixelSnoop and it is used like this:

// Calculate a simple sum over all of the pixels
// in the snooped bitmap. bitmap is a valid Bitmap object
long snoopSum = 0;
// Create a BmpPixelSnoop wrapper for bitmap
using (var snoop = new BmpPixelSnoop(bitmap))
{
    for (int j = 0; j != snoop.Height; j++)
    {
        for (int i = 0; i != snoop.Width; i++)
        {
            // We call GetPixel() on snoop rather
            // than bitmap as it's much faster!
            var col = snoop.GetPixel(i, j);
            snoopSum += col.R +
                        col.G +
                        col.B;
        }
    }
}

First a BmpPixelSnoop object is created to wrap the bitmap, GetPixel() and SetPixel() can then be called on it. When the BmpPixelSnoop object is destroyed (on leaving the using() block) the original bitmap will be unlocked. It is important to note, that while the bitmap is being snooped the original bitmap object cannot be accessed as it’s locked! Currently BmpPixelSnoop only works for bitmaps with a Pixel Format of PixelFormat.Format32bppArgb which is the default format for Bitmaps (if you don’t specify an alternative when creating them).

So for a little extra complication you get easy & fast access to the bitmap data – but how much faster than the native Get/SetPixel() is it? My (non scientific) tests seem to indicate that it’s about 10 times faster, which is fast enough for simple imaging tasks. It is still quite inefficient however, this is a result of wanting to provide the same Get/SetPixel() interface as System.Drawing.Bitmap – for example, GetPixel() always returns all of the pixel data even if you just want to access the red component and hence is slower than it needs to be in this case. I may add extra accessor methods in the future to cater for other usage patterns and greater efficiency.

The code can be found in the git-hub repo: https://github.com/kgodden/DotNetPixelSnoop.

The class is defined in BmpPixelSnoop.cs, there is also some test code to check correctness and performance in Program.cs.

Here is the code:

//   Copyright 2019 Kevin Godden
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
using System;
using System.Drawing;
using System.Drawing.Imaging;
/// 
/// Wraps a System.Drawing.Bitmap and provides faster
/// GetPixel() and SetPixel() functions for pixel access.
/// 
/// NB While the snoop object is in scope the wrapped
/// bitmap object is locked and cannot be used 
/// as normal.  Once you have finished snooping
/// on a bitmap object, dispose of the snooper to
/// unlock the bitmap and gain normal access to 
/// it again, it is best to employ the 'using' keyword
/// to effectivly manage the snooper's scope as follows:
/// 
/// 
/// using (var snoop = new BmpPixelSnoop(myBitmap))
/// { 
/// 
///     // Snoop away!
///     var pixel = snoop.GetPixel(0, 0);
///     
/// } // Snoop goes out of scope here and bitmap is unlocked
/// 
/// This class is marked as 'unsafe' so to use it in your project
/// you must have the 'Allow unsafe code' setting checked in the
/// project settings.
/// 
/// 
unsafe class BmpPixelSnoop : IDisposable
{
    // A reference to the bitmap to be wrapped
    private readonly Bitmap wrappedBitmap;
    // The bitmap's data (once it has been locked)
    private BitmapData data = null;
    // Pointer to the first pixel
    private readonly byte* scan0;
    // Number of bytes per pixel
    private readonly int depth;
    // Number of bytes in an image row
    private readonly int stride;
    // The bitmap's width
    private readonly int width;
    // The bitmap's height
    private readonly int height;
    /// 
    /// Constructs a BmpPixelSnoop object, the bitmap
    /// object to be wraped is passed as a parameter.
    /// 
    /// The bitmap to snoop
    public BmpPixelSnoop(Bitmap bitmap)
    {
        wrappedBitmap = bitmap ?? throw new ArgumentException("Bitmap parameter cannot be null", "bitmap");
        // Currently works only for: PixelFormat.Format32bppArgb
        if (wrappedBitmap.PixelFormat != PixelFormat.Format32bppArgb)
            throw new System.ArgumentException("Only PixelFormat.Format32bppArgb is supported", "bitmap");
        // Record the width & height
        width = wrappedBitmap.Width;
        height = wrappedBitmap.Height;
        // So now we need to lock the bitmap so that we can gain access
        // to it's raw pixel data.  It will be unlocked when this snoop is 
        // disposed.
        var rect = new Rectangle(0, 0, wrappedBitmap.Width, wrappedBitmap.Height);
        try
        {
            data = wrappedBitmap.LockBits(rect, ImageLockMode.ReadWrite, wrappedBitmap.PixelFormat);
        }
        catch (Exception ex)
        {
            throw new System.InvalidOperationException("Could not lock bitmap, is it already being snooped somewhere else?", ex);
        }
        // Calculate number of bytes per pixel
        depth = Bitmap.GetPixelFormatSize(data.PixelFormat) / 8; // bits per channel
        // Get pointer to first pixel
        scan0 = (byte*)data.Scan0.ToPointer();
        // Get the number of bytes in an image row
        // this will be used when determining a pixel's
        // memory address.
        stride = data.Stride;
    }
    /// 
    /// Disposes BmpPixelSnoop object
    /// 
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
     /// 
    /// Disposes BmpPixelSnoop object, we unlock
    /// the wrapped bitmap.
    /// 
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (wrappedBitmap != null)
                wrappedBitmap.UnlockBits(data);
        }
        // free native resources if there are any.
    }
    /// 
    /// Calculate the pointer to a pixel at (x, x)
    /// 
    /// The pixel's x coordinate
    /// The pixel's y coordinate
    /// A byte* pointer to the pixel's data
    private byte* PixelPointer(int x, int y)
    {
        return scan0 + y * stride + x * depth;
    }
    /// 
    /// Snoop's implemetation of GetPixel() which is similar to
    /// Bitmap's GetPixel() but should be faster.
    /// 
    /// The pixel's x coordinate
    /// The pixel's y coordinate
    /// The pixel's colour
    public System.Drawing.Color GetPixel(int x, int y)
    {
        // Better do the 'decent thing' and bounds check x & y
        if (x < 0 || y < 0 || x >= width || y >= width)
            throw new ArgumentException("x or y coordinate is out of range");
        int a, r, g, b;
        // Get a pointer to this pixel
        byte* p = PixelPointer(x, y);
        // Pull out its colour data
        b = *p++;
        g = *p++;
        r = *p++;
        a = *p;
        // And return a color value for it (this is quite slow
        // but allows us to look like Bitmap.GetPixel())
        return System.Drawing.Color.FromArgb(a, r, g, b);
    }
    /// 
    /// Sets the passed colour to the pixel at (x, y)
    /// 
    /// The pixel's x coordinate
    /// The pixel's y coordinate
    /// The value to be assigned to the pixel
    public void SetPixel(int x, int y, System.Drawing.Color col)
    {
        // Better do the 'decent thing' and bounds check x & y
        if (x < 0 || y < 0 || x >= width || y >= width)
            throw new ArgumentException("x or y coordinate is out of range");
        // Get a pointer to this pixel
        byte* p = PixelPointer(x, y);
        // Set the data
        *p++ = col.B;
        *p++ = col.G;
        *p++ = col.R;
        *p = col.A;
    }
    /// 
    /// The bitmap's width
    /// 
    public int Width { get { return width; } }
    // The bitmap's height
    public int Height { get { return height; } }
}

Here is some sample output from the colsone based test program, showing relative times:

Testing GetPixel()
GetPixel() OK
Testing SetPixel()
SetPixel() OK
Testing GetPixel() Speed
Bitmap.GetPixel() took 759ms, BmpPixelSnoop.GetPixel() took 67ms
Testing SetPixel() Speed
Bitmap.SetPixel() took 907ms, BmpPixelSnoop.SetPixel() took 72ms