Question

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;
}
Was it helpful?

Solution

You are using the incorrect overload of DrawImage. You should be using the one where you specify the Src and Dest rects.

graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);

Try that and let me know in comments if it doesn't work.

OTHER TIPS

i suspect the answer lies in the way the library actually makes the modification. it just copy and pastes around some blocks of memory. the resolution specifies the number of bits/bytes used per pixel. in order to know how many bytes he needs to copy, he needs to know how many bits/bytes per pixel is used.

therefore i think this is a simple multiplication followed by a memcopy.

regards

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top