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

Squaring an image

Feb 13 at 8:16 PM
I need help converting a command that that will convert the image proportions to a square, that is, equal width and height without distorting the image, and fill the background with white. Here is my old code:

convert.exe "C:\input_rectangle.jpg" -virtual-pixel background -background white -set option:distort:viewport "%[fx:max(w,h)]x%[fx:max(w,h)]-%[fx:max((h-w)/2,0)]-%[fx:max((w-h)/2,0)]" -filter point -distort SRT 0 +repage "C:\output_square.jpg"

This is as far as I got, but it doesn't work:
            image.VirtualPixelMethod = VirtualPixelMethod.Background;
            image.BackgroundColor = new MagickColor(System.Drawing.Color.White);
            image.SetArtifact("option:distort:viewport", "%[fx:max(w,h)]x%[fx:max(w,h)]-%[fx:max((h-w)/2,0)]-%[fx:max((w-h)/2,0)]");

            image.FilterType = FilterType.Point;

            image.Distort(DistortMethod.ScaleRotateTranslate, new double[] { 0 });
            image.RePage();
Thanks in advance!
Coordinator
Feb 13 at 8:51 PM
Edited Feb 13 at 9:23 PM
You almost got it! The name of SetArtifact should not contain option: and you will need to format the expression yourself. This is not done automatically. Below is an example of how you could do this:
using (MagickImage image = new MagickImage(@"C:\input_rectangle.jpg"))
{
  // -virtual-pixel background
  image.VirtualPixelMethod = VirtualPixelMethod.Background;

  // -background white
  image.BackgroundColor = MagickColors.White;

  // -set option:distort:viewport "%[fx:max(w,h)]x%[fx:max(w,h)]-%[fx:max((h-w)/2,0)]-%[fx:max((w-h)/2,0)]"
  string expression = image.FormatExpression("%[fx:max(w,h)]x%[fx:max(w,h)]-%[fx:max((h-w)/2,0)]-%[fx:max((w-h)/2,0)]");
  image.SetArtifact("distort:viewport", expression);

  // An alternative implementation would be:
  int size = Math.Max(image.Width, image.Height); // [fx:max(w,h)]
  int x = -Math.Max((image.Height - image.Width) / 2, 0);// -[fx:max((h-w)/2,0)]
  int y = -Math.Max((image.Width - image.Height) / 2, 0);// -[fx:max((w-h)/2,0)]
  MagickGeometry geometry = new MagickGeometry(x, y, size, size);
  image.SetArtifact("distort:viewport", geometry.ToString());

  // -filter point
  image.FilterType = FilterType.Point;

  // -distort SRT 0 
  image.Distort(DistortMethod.ScaleRotateTranslate, 0); // params

  // +repage
  image.RePage();

  image.Write(@"C:\output_square.jpg");
}
Feb 13 at 9:50 PM
It works perfectly! Thank you!