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
Next Post
The Asylum  19 Dec 2003
Prior Post
Approaches to Development - Hacking  06 Dec 2003
Related Posts
Types behaving badly  14 Apr 2018
Implementing Value Equality  07 Apr 2018
Implementing Entity Equality  31 Mar 2018
Equality and GetHashCode  24 Mar 2018
Types of Equality  10 Mar 2018
Why is Equality important in .NET?  03 Mar 2018
Invalid Build Configuration: Debug|BNB  14 May 2011
Intersect and Except  24 Jul 2008
Streams in .NET  26 Dec 2003
Streams in .NET  20 Nov 2003
December 2003