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

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM