C# Bitmap deep copy

今天在研究一个关于 Bitmap deep copy 的问题, 经过一系列的查询,在StackOverFlow上面找到了答案,遂记录下来:

  public static Bitmap DeepCopyBitmap(Bitmap bitmap)
        {
            try
            {
                Bitmap dstBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat);
                return dstBitmap;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : {0}", ex.Message);
                return null;
            }
        }

解析:

new Bitmap(Image img) 方法会改变图片色彩格式 (BitMap.PixelFormat)。

bitmap.Clone() 方法会生成一个shadow copy。

当使用 bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat) 类似于做BitMap.LockBits操作,会生成一个新的内存。

参考:

http://stackoverflow.com/questions/5882815/how-to-create-a-bitmap-deep-copy

http://stackoverflow.com/questions/12709360/whats-the-difference-between-bitmap-clone-and-new-bitmapbitmap/13935966#13935966

补充:由于我是用的是Framework2.0, 所以上述deep copy 未成功!!!,自己重新实现了一下

public static Bitmap DeepCopyBitmap(Bitmap bitmap)

{
            try
            {               

                Bitmap dstBitmap = null;                
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(ms, bitmap);
                    ms.Seek(0, SeekOrigin.Begin);
                    dstBitmap = (Bitmap)bf.Deserialize(ms);
                    ms.Close();
                }                
                return dstBitmap;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }

}

原文地址:https://www.cnblogs.com/atuotuo/p/6125430.html