public static void Main()
var (bounds, boundPoints) = GrabBountryRectangle(item);
var whit = new ImageMagick.MagickImage()
VirtualPixelMethod = ImageMagick.VirtualPixelMethod.Transparent,
BackgroundColor = ImageMagick.MagickColor.FromRgba(0, 0, 0, 0),
var whitRatio = whit.Width / (float)whit.Height;
var preDistortW = (int)Math.Round(Math.Max(bounds.Width, bounds.Height * whitRatio));
var preDistortH = (int)Math.Round(Math.Max(bounds.Height, bounds.Width * whitRatio));
whit.Scale((uint)preDistortW, (uint)preDistortH);
var scaledW = whit.Width;
var scaledH = whit.Height;
whit.Extent((uint)preDistortW, (uint)preDistortH, ImageMagick.Gravity.Northwest);
whit.Distort(ImageMagick.DistortMethod.Perspective, new double[] {
0, 0, boundPoints.X1, boundPoints.Y1,
0, scaledH, boundPoints.X2, boundPoints.Y2,
scaledW, 0, boundPoints.X3, boundPoints.Y3,
scaledW, scaledH, boundPoints.X4, boundPoints.Y4,
private static (System.Drawing.Rectangle, FourPoints) GrabBountryRectangle(Item item)
var roundX1 = (int)Math.Round(item.X1);
var roundY1 = (int)Math.Round(item.Y1);
var roundX2 = (int)Math.Round(item.X2);
var roundY2 = (int)Math.Round(item.Y2);
var roundX3 = (int)Math.Round(item.X3);
var roundY3 = (int)Math.Round(item.Y3);
var roundX4 = (int)Math.Round(item.X4);
var roundY4 = (int)Math.Round(item.Y4);
var left = Math.Min(Math.Min(roundX1, roundX2), Math.Min(roundX3, roundX4));
var right = Math.Max(Math.Max(roundX1, roundX2), Math.Max(roundX3, roundX4));
var top = Math.Min(Math.Min(roundY1, roundY2), Math.Min(roundY3, roundY4));
var bottom = Math.Max(Math.Max(roundY1, roundY2), Math.Max(roundY3, roundY4));
var bounds = new System.Drawing.Rectangle(left, top, right - left, bottom - top);
var boundPoints = new FourPoints
return (bounds, boundPoints);
public int X1 { get; set; }
public int Y1 { get; set; }
public int X2 { get; set; }
public int Y2 { get; set; }
public int X3 { get; set; }
public int Y3 { get; set; }
public int X4 { get; set; }
public int Y4 { get; set; }
public void Scale(double s, int offsetX = 0, int offsetY = 0)
X1 = (int)Math.Round(X1 * s) + offsetX;
Y1 = (int)Math.Round(Y1 * s) + offsetY;
X2 = (int)Math.Round(X2 * s) + offsetX;
Y2 = (int)Math.Round(Y2 * s) + offsetY;
X3 = (int)Math.Round(X3 * s) + offsetX;
Y3 = (int)Math.Round(Y3 * s) + offsetY;
X4 = (int)Math.Round(X4 * s) + offsetX;
Y4 = (int)Math.Round(Y4 * s) + offsetY;
public float X1 { get; set; }
public float Y1 { get; set; }
public float X2 { get; set; }
public float Y2 { get; set; }
public float X3 { get; set; }
public float Y3 { get; set; }
public float X4 { get; set; }
public float Y4 { get; set; }