I'm dealing with Bitmaps in my application and for some purposes I need to create a deep copy of the Bitmap. Is there an elegant way how to do it?
I tried
Bitmap deepCopy = original.Clone();
,well apparently this doesn't create a deep copy, but shallow one. My next attempt was to create a new Bitmap
Bitmap deepCopy = new Bitmap(original);
Unfortunately this constructor is Bitmap(Image), not Bitmap(Bitmap) and Bitmap(Image) will convert my nice 8bppIndexed Pixelformat into a different one.
Another attempt was to use of a MemoryStream
public static Bitmap CreateBitmapDeepCopy(Bitmap source)
{
Bitmap result;
using (MemoryStream stream = new MemoryStream())
{
source.Save(stream, ImageFormat.Bmp);
stream.Seek(0, SeekOrigin.Begin);
result = new Bitmap(stream);
}
return result;
}
Well, this doesn't work either, since the MemoryStream has to be opened during the whole lifetime of Bitmap.
So, I've summed up all my deadends and I'd really like to see a nice elegant way of creating a Bitmap deep copy. Thanks for that :)