Fast image pixel access with GDI+ and .net

I have yet again hit a brick wall with regards to speed in processing dynamic images server side using System.Drawing in  As I have covered in a previous article regarding image cropping I have had difficulty in the past finding a quick way to access each individual pixel of an image.  Unfortunately my algorithm was only the result of a having to deal with a slow getpixel method.  Using what I had at the time that was the best I could come up with.

Enter and a wealth of additional capability.  I came across a great set of articles from One  great article in particular pertained to my issue exactly.  Direct memory access to pixel data using lock bits.  Here is a direct link.  It is not often that I find exactly what I need, but this was perfect.

Here is a snippet of Bob’s code, I also added some lines to elaborate where you can access the other 3 components of the image data Bob’s code did not illustrate.

     BitmapData bmd=bm.LockBits(new Rectangle(0, 0, 10, 10), System.Drawing.Imaging.ImageLockMode.ReadOnly, bm.PixelFormat);
      int PixelSize=4;
      for(int y=0; y< bmd.height; y++)
        byte* row=(byte *)bmd.Scan0+(y*bmd.Stride);
        for(int x=0; x< bmd.width ; x++>
          row[x*PixelSize]=255; //blue component
          row[(x*PixelSize)+1] = 255; // green component
          row[(x*PixelSize)+2] = 255; // red component
          row[(x*PixelSize)+3] = 255; // alpha component

So what is the advantage of this? One word SPEED. You can accomplish the same thing (reading,writing) pixel data using the managed code in system.drawing (getpixel() ), but you will find very quickly if you are doing any serious processing it is very slow.  This method is far superior assuming you know the risk (you can potentially mess with memory you aren’t supposed to).  I’m happy to report I have an efficient cropping function now that appears will speed up alot of code already in use.

Be Sociable, Share!


No comments yet, be the first.

Add a Comment