I used the below code to clone a bitmap image without locking the original file. But i am facing an issue that cloned image (.Gif) is not the same as the original image. Especially, the color of the cloned image is not proper.
Am I doing anything wrong? Is any better way to have Image in memory and original file deleted from hard disk?
Code:
private Bitmap CloneImage(Bitmap src)
{
if (src == null)
return src;
Bitmap bitmap = new Bitmap(src.Size.Width, src.Size.Height, src.PixelFormat);
System.Drawing.Rectangle bounds = new System.Drawing.Rectangle(0, 0, src.Width, src.Height);
System.Drawing.Imaging.BitmapData bmpData = src.LockBits(bounds, System.Drawing.Imaging.ImageLockMode.ReadWrite, src.PixelFormat);
System.Drawing.Imaging.BitmapData newBmpData = bitmap.LockBits(bounds, System.Drawing.Imaging.ImageLockMode.ReadWrite, src.PixelFormat);
IntPtr bPtr = bmpData.Scan0;
IntPtr nbPtr = newBmpData.Scan0;
int bytes = Math.Abs(bmpData.Stride) * src.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(bPtr, rgbValues, 0, bytes);
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, nbPtr, bytes);
bitmap.UnlockBits(newBmpData);
src.UnlockBits(bmpData);
return bitmap;
}
Original Image:
Cloned image: