如何创建Bitmap深层副本

我在我的应用程序中处理Bitmaps,出于某些目的,我需要创建Bitmap的深层副本。 有一种优雅的方式怎么做?

我试过了

Bitmap deepCopy = original.Clone(); 

,显然这不是创造一个深刻的副本,而是浅薄的副本。 我的下一个尝试是创建一个新的位图

 Bitmap deepCopy = new Bitmap(original); 

不幸的是,这个构造函数是Bitmap(Image),而不是Bitmap(Bitmap),而Bitmap(Image)会将我漂亮的8bppIndexed Pixelformat转换为另一个。

另一种尝试是使用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; } 

好吧,这也不起作用,因为必须在Bitmap的整个生命周期内打开MemoryStream。

所以,我总结了所有的后果,我真的很想看到一个很好的方法来创建一个Bitmap深层副本。 感谢那 :)

 B.Clone(new Rectangle(0, 0, B.Width, B.Height), B.PixelFormat) 

您可以序列化位图,然后反序列化它。 位图是可序列化的。

我偶然发现的另一种方法就是旋转或翻转图像。 在引擎盖下似乎创建了一个全新的位图副本。 进行两次旋转或翻转可以使您获得原始图像的精确副本。

 result.RotateFlip(RotateFlipType.Rotate180FlipX); result.RotateFlip(RotateFlipType.Rotate180FlipX); 

假设您已经有一个名为original的位图,其中包含一些内容

 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); } 

这应创建相同大小的副本,并将原始内容绘制到副本中。