For some odd reason, Cloning a .net Bitmap doesn’t actually give you a different image. Oh, sure, the object returned from Bitmap.Clone() is a Bitmap, and it is a different instance of the Bitmap class from the one you started with. But it’s not a different image.

The Bitmap class in .net is a wrapper around GDI+ functionality - and it seems that Cloning a Bitmap just gives you a separate wrapper for the same underlying GDI+ image.

This leaves you in the wonderful position of being having two apparently distinct Bitmaps that are coupled - if you try to find out the width of Bitmap A while you’re modifying Bitmap B, you suddenly are faced with a “Bitmap Region is already locked” Illegal Operation exception.

The solution? Don’t use this:

Bitmap aCopy = (Bitmap)aImage.Clone();

Instead, use the Cloning constructor of Bitmap like this:

      Bitmap aCopy = new Bitmap(aImage);

I hope this saves you more time than not knowing it cost me!


blog comments powered by Disqus