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!

Comments

blog comments powered by Disqus
Next Post
The Asylum  19 Dec 2003
Prior Post
Approaches to Development - Hacking  06 Dec 2003
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
Archives
December 2003
2003