C# Bitmap deep copy

本文介绍了两种实现Bitmap深拷贝的方法:一种是通过Clone方法创建一个阴影副本;另一种是利用BinaryFormatter序列化和反序列化来实现。文章还讨论了不同方法在不同.NET Framework版本中的适用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在研究一个关于 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值