This project has moved. For the latest updates, please go here.

Cropping image

Aug 5, 2015 at 10:39 AM
Hello
I wrote the function for cropping image but I believe that it is not optimal.
How can I increase the performance of my code?

Detailed task:
function should to transform existing image(cannot create a new image as the result of operation and return it) because needs to save existing profiles like as exif, iptc, etc

my idea: fill image with backgorundColor then resize it to needed size and after that combine with the clone of original image
public class Cropper
{
    public void Crop(MagickImage image, int x, int y, int width, int height, Color backgroundColor)
    {
        using (MagickImage clone = image.Clone())
        {
            image.FillColor = new MagickColor(backgroundColor);
            image.Draw(new DrawableRectangle(0, 0, Width, Height));
            image.Resize(new MagickGeometry(width, height) { IgnoreAspectRatio = true });
            image.Composite(clone, new MagickGeometry(-x, -y, width, height));
        }
    }
}
Coordinator
Aug 6, 2015 at 10:46 AM
Why aren't you using the Crop method of MagickImage?
Aug 6, 2015 at 10:53 AM
It does not work properly in following cases:
Image
Coordinator
Aug 6, 2015 at 11:30 AM
That might be a bug or a missing feature. I will take a look at it tonight when I am back home.
Coordinator
Aug 6, 2015 at 8:39 PM
Do you want to include the 'virtual pixels'? Or do you just want the part of the image?
Aug 7, 2015 at 6:28 AM
I want to include 'virtual pixels' colored with backgroundColor.
Coordinator
Aug 7, 2015 at 7:06 AM
Edited Aug 7, 2015 at 7:20 AM
You can use the Extent method of MagickImage to do this.
int x = -100;
int y = -100;
int width = 500;
int height = 200;

using (MagickImage image = new MagickImage("logo:"))
{
  image.BackgroundColor = new MagickColor("blue");
  image.Extent(new MagickGeometry(x, y, width, height));
  image.Write("output.png");
}
p.s. I will add a new overload in the next version so you can do this:
image.Extent(x, y, width, height);
Aug 12, 2015 at 11:53 AM
Thanks!