How to create a Bitmap deep copy

前端 未结 5 1626
礼貌的吻别
礼貌的吻别 2020-12-18 18:49

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

相关标签:
5条回答
  • 2020-12-18 19:06

    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);
    
    0 讨论(0)
  • 2020-12-18 19:09

    Suppose you already have a bitmap called original with something in it

    Bitmap original = new Bitmap( 200, 200 );     
    Bitmap copy = new Bitmap(original.Width, original.Height);
    using (Graphics graphics = Graphics.FromImage(copy))
    {
      Rectangle imageRectangle = new Rectangle(0, 0, copy.Width, copy.Height);
      graphics.DrawImage( original, imageRectangle, imageRectangle, GraphicsUnit.Pixel);
    }
    

    This should create a copy of the same size, and draw the original into the copy.

    0 讨论(0)
  • 2020-12-18 19:11
    B.Clone(new Rectangle(0, 0, B.Width, B.Height), B.PixelFormat)
    
    0 讨论(0)
  • 2020-12-18 19:16

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

    0 讨论(0)
  • 2020-12-18 19:18

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

    It works for me.

    Bitmap deepCopy = new Bitmap(original);
    
    0 讨论(0)
提交回复
热议问题