zoukankan      html  css  js  c++  java
  • 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;
                }

    }

  • 相关阅读:
    【POJ】2778 DNA Sequence(AC自动机+矩阵快速幂)
    【HDU】4352 XHXJ's LIS(数位dp+状压)
    【BZOJ】1756: Vijos1083 小白逛公园(线段树)
    【POJ】1062 昂贵的聘礼 (最短路)
    【Codeforces】Codeforces Round #491 (Div. 2) (Contest 991)
    【Codeforces】Codeforces Round #492 (Div. 2) (Contest 996)
    【Codeforces】Educational Codeforces Round 46(Contest 1000)
    【POJ】1935 Journey(树形dp)
    【UVALive】4094 WonderTeam(神结论)
    【POJ】1185 炮兵阵地(状压dp)
  • 原文地址:https://www.cnblogs.com/atuotuo/p/6125430.html
Copyright © 2011-2022 走看看