views:

85

answers:

2

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;
}
A: 

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

Atmocreations
Shouldn't the format of the image define how many bytes per pixel? Is it RGB? RGBA? Are they ints, longs or floats? And then just copy the pixels I'm telling it to.
J. Pablo Fernández
well yes, it does. but the format has only information how to store the data. depending on the format, it might be possible that the resolution is variable and therefore not precisely known by the format. i guess floats don't apply.what type of format is it? or is it unknown?what happens if you omit the line result.SetResolution(72, 72);regards
Atmocreations
I think video cards use RGBA with floats. If I omit the resolution and let's say, I crop(0, 0, 100, 100) I get an image of 100 by 100 with a piece of the original picture of about 60 by 60 stretched out.
J. Pablo Fernández
A video card uses whatever format you tell it too.
Pod
+1  A: 

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.

Daniel Magliola