title: Creating a completely new copy of bitmap from a bitmap in C#
body: <p>I need a deep copy of bitmap from another bitmap. Now, most of the solutions say something like <a href="https://stackoverflow.com/a/5882913/5330223">this</a>, which is not a <strong>deep copy</strong>. Meaning that when I lock the original bitmap, then the copy gets locked too, as the clone is a <strong>shallow copy</strong> of the original bitmap. Now the following seems to work for me, but I am not sure that will work in all cases.</p>
  
  <pre><code>public static Bitmap GetCopyOf(Bitmap originalImage)
  {
      Rectangle rect = new Rectangle(0, 0, originalImage.Width, originalImage.Height);
      Bitmap retrunImage = new Bitmap(originalImage.Width, originalImage.Height, originalImage.PixelFormat);
      BitmapData srcData = originalImage.LockBits(rect, ImageLockMode.ReadOnly, originalImage.PixelFormat);
      BitmapData destData = retrunImage.LockBits(rect, ImageLockMode.WriteOnly, originalImage.PixelFormat);
      int dataLength = Math.Abs(srcData.Stride) * srcData.Height;
      byte[] data = new byte[dataLength];
      Marshal.Copy(srcData.Scan0, data, 0, data.Length);
      Marshal.Copy(data, 0, destData.Scan0, data.Length);
      destData.Stride = srcData.Stride;
      if (originalImage.Palette.Entries.Length != 0)
          retrunImage.Palette = originalImage.Palette;
      originalImage.UnlockBits(srcData);
      retrunImage.UnlockBits(destData);
      return retrunImage;
  }
  </code></pre>
  
  <p>I need better and more elegant way of doing this. Otherwise, just point me some cases where the above code may fail. TIA</p>