Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Bitmap deep copy

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 :)

like image 437
Biggles Avatar asked May 04 '11 11:05

Biggles


4 Answers

B.Clone(new Rectangle(0, 0, B.Width, B.Height), B.PixelFormat)
like image 64
George Duckett Avatar answered Oct 23 '22 23:10

George Duckett


Another way I stumbled on that achieves the same thing is to rotate or flip the image. Under the hood that seems to create a completely new copy of the bitmap. Doing two rotations or flips lets you end up with an exact copy of the original image.

result.RotateFlip(RotateFlipType.Rotate180FlipX);
result.RotateFlip(RotateFlipType.Rotate180FlipX);
like image 39
sipsorcery Avatar answered Oct 24 '22 01:10

sipsorcery


My environment:Windows 10, Visual Studio 2015, Framework 4.5.2

It works for me.

Bitmap deepCopy = new Bitmap(original);
like image 2
ToyAuthor X Avatar answered Oct 23 '22 23:10

ToyAuthor X


You could serialize the bitmap and then deserialize it. Bitmap is serializable.

like image 1
Emond Avatar answered Oct 24 '22 00:10

Emond