Search code examples
c#bitmapclone

What's the difference between Bitmap.Clone() and new Bitmap(Bitmap)?


As far as I can tell, there are two ways of copying a bitmap.

Bitmap.Clone()

Bitmap A = new Bitmap("somefile.png");
Bitmap B = (Bitmap)A.Clone();

new Bitmap()

Bitmap A = new Bitmap("somefile.png");
Bitmap B = new Bitmap(A);

How do these approaches differ? I'm particularly interested in the difference in terms of memory and threading.


Solution

  • It is the common difference between a "deep" and a "shallow" copy, also an issue with the almost-deprecated IClonable interface. The Clone() method creates a new Bitmap object but the pixel data is shared with the original bitmap object. The Bitmap(Image) constructor also creates a new Bitmap object but one that has its own copy of the pixel data.

    Lots of questions about Clone() at SO where the programmer hopes that it avoids the typical trouble with bitmaps, the lock on the file from which it was loaded. It doesn't. A possibly practical usage is avoiding trouble with a library method that inappropriately calls Dispose() on a passed bitmap.

    The overloads may be useful, taking advantage of the pixel format conversion or the cropping options.