I wrote a method to crop images in C#. It does it by creating a new Bitmap and drawing onto it a specified rectangle (the area to be cropped) from the original image.
For the images I've tried with it was generating wrong results. The size of the resulting image was right, but the content was it. It was like if the image has been scaled up by 2 and then cropped. Eventually adding this line fixed it:
result.setResolution(72, 72)
But why do I need a resolution? I'm just working with pixels, never with inches or centimeters. Also, what would then be the correct resolution?
The full code is this extension method:
public static Bitmap Crop(this Image image, int x, int y, int width, int height) {
Bitmap result = new Bitmap(width, height);
result.SetResolution(72, 72);
// Use a graphics object to draw the resized image into the bitmap.
using (Graphics graphics = Graphics.FromImage(result)) {
// High quality.
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// Draw the image into the target bitmap.
graphics.DrawImage(image, 0, 0, new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
}
return result;
}