public static class BitmapHelper {
public static Bitmap Clone(Bitmap bmp) {
var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
Bitmap newbmp = new Bitmap(rect.Width, rect.Height);
using (Graphics gfx = Graphics.FromImage(newbmp)) {
gfx.InterpolationMode = InterpolationMode.High;
gfx.PixelOffsetMode = PixelOffsetMode.None;
gfx.DrawImage(bmp, rect, rect, GraphicsUnit.Pixel);
}
return newbmp;
}
}
Most of the time, this does create an identical copy, but if the original Bitmap passed to Clone was created by painting a section from a larger Bitmap where the section extended to the right-most edge of the larger Bitmap, then the copy I get back will have slightly altered pixels on its right-most edge.
What am I doing wrong?
The code that creates the original looks like this:
var SmallerImage = new Bitmap(_sqSize, _sqSize);
using (var gfx = Graphics.FromImage(SmallerImage)) {
gfx.InterpolationMode = InterpolationMode.High;
gfx.PixelOffsetMode = PixelOffsetMode.None;
gfx.DrawImage(LargerImage,
new Rectangle(0, 0, _sqSize, _sqSize),
new Rectangle(p.X, p.Y, _sqSize, _sqSize),
GraphicsUnit.Pixel);
}
The important thing to know there is that Point p and _sqSize are such that the source rectangle (the second rectangle in the DrawImage call) goes right up to the right-most edge of LargerImage.
This same code WILL create an identical copy when Point p and _sqSize are such that the source rectangle does not butt up to the right edge of LargerImage.
Can anyone tell me why this happens?
Or, can someone tell me how to RELIABLY create an EXACT pixel-for-pixel duplicate of a Bitmap? Seems like it ought to be easy, but I can't seem to do it.
new Bitmap(bmp)
has the same problems as my Clone method. bmp.Clone()
does seem to work, but it has problems under the covers (something about it not being a deep copy -- sharing data with the original) and using it breaks my code in many ways.