Gup3rSuR4c
Gup3rSuR4c

Reputation: 9490

What's wrong with this image cropper?

I'm making a cropping tool for images and I can't for the life of me figure out why it's producing the images that it's producing...

I'm following the accepted answer here, but its still being weird... Here's my code:

public void Crop(
    string FileName,
    Crop Crop) {
    using (Bitmap Source = ((Bitmap)Image.FromFile(FileName))) {
        using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
            using (Graphics Graphics = Graphics.FromImage(Target)) {
                Graphics.DrawImage(Source, new Rectangle(new Point(Crop.Left, Crop.Top), new Size(Crop.Width, Crop.Height)), new Rectangle(new Point(0, 0), new Size(Target.Width, Target.Height)), GraphicsUnit.Pixel);
            };

            Target.Save((FileName + ".temp"), JpegCodecInfo, HighQualityEncoder);
        };
    };


    this.NormalizeFileName(FileName);
}

Please help me. I'm attaching an image of what I'm getting...alt text

UPDATE

For @Aaronontheweb, here's the Crop class and how it's populated:

public class Crop {
    [Required]
    public short Height { get; set; }

    [Required]
    public short Left { get; set; }

    [Required]
    public short Top { get; set; }

    [Required]
    public short Width { get; set; }
}

And the jQuery that populates it:

$("#Image input:submit").bind("click", function () {
    $("#Crop\\.Height").val(Crop.height());
    $("#Crop\\.Left").val(Crop.position().left);
    $("#Crop\\.Top").val(Crop.position().top);
    $("#Crop\\.Width").val(Crop.width());
});

UPDATE 2

Never mind, I got it. I took a nap after asking my question just to clear my head and when I looked at it again after, I decided to switch the two rectangles and see what happens. Well, guess what, that fixed it.

At this point I would have to say that the names given in the API documentation are deceptive. For example the docs refer to the output image as source and the input image as display. Perhaps the API should be updated to have better naming?

Upvotes: 3

Views: 364

Answers (1)

TBohnen.jnr
TBohnen.jnr

Reputation: 5119

In the following line:

Graphics.DrawImage(Source, new Rectangle(new Point(Crop.Left, Crop.Top), new Size(Crop.Width, Crop.Height)), new Rectangle(new Point(0, 0), new Size(Target.Width, Target.Height)), GraphicsUnit.Pixel);

Make sure the Crop.Left and Crop.Top is set to 0, otherwise it will start setting the pixels at the weird offset you are getting. You can also just replace it with the following line to test:

Graphics.DrawImage(Source, new Rectangle(new Point(0,0), new Size(Crop.Width, Crop.Height)), new Rectangle(new Point(0, 0), new Size(Target.Width, Target.Height)), GraphicsUnit.Pixel);

Upvotes: 3

Related Questions