将位图裁剪为 1:1 纵横比

Cropping a Bitmap to 1:1 Aspect Ratio

我有如下宽高比的位图,或者可能是任何宽高比..

当用户指定一个选项时,我需要一种方法来从这些图像中裁剪掉周围的部分,以便生成具有 1:1 纵横比的图像。 像这样

我想我会在这些图像中取中心点并剪掉边..

我在web平台上找到了这个方法..但是Bitmap没有Crop方法

 public static WebImage BestUsabilityCrop(WebImage image, decimal targetRatio)
        {
            decimal currentImageRatio = image.Width / (decimal)image.Height;
            int difference;

            //image is wider than targeted
            if (currentImageRatio > targetRatio)
            {
                int targetWidth = Convert.ToInt32(Math.Floor(targetRatio * image.Height));
                difference = image.Width - targetWidth;
                int left = Convert.ToInt32(Math.Floor(difference / (decimal)2));
                int right = Convert.ToInt32(Math.Ceiling(difference / (decimal)2));
                image.Crop(0, left, 0, right);
            }
            //image is higher than targeted
            else if (currentImageRatio < targetRatio)
            {
                int targetHeight = Convert.ToInt32(Math.Floor(image.Width / targetRatio));
                difference = image.Height - targetHeight;
                int top = Convert.ToInt32(Math.Floor(difference / (decimal)2));
                int bottom = Convert.ToInt32(Math.Ceiling(difference / (decimal)2));
                image.Crop(top, 0, bottom, 0);
            }
            return image;
        }

请提供解决此问题的方法。

你可以这样使用:

public static Image Crop(Image source)
{
    if (source.Width == source.Height) return source;
    int size = Math.Min(source.Width, source.Height);
    var sourceRect = new Rectangle((source.Width - size) / 2, (source.Height - size) / 2, size, size);
    var cropped = new Bitmap(size, size);
    using (var g = Graphics.FromImage(cropped))
        g.DrawImage(source, 0, 0, sourceRect, GraphicsUnit.Pixel);
    return cropped;
}

这会从中心裁剪。如果你想从 bottom/right 裁剪,那么只需使用 var sourceRect = new Rectangle(0, 0, size, size);.