将位图裁剪为1:1宽高比

时间:2016-04-01 15:44:56

标签: c# .net bitmap system.drawing

我的比特图具有如下宽高比,或者可以是任何宽高比。

enter image description here

enter image description here

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

enter image description here

我想我会在这些图像中占据中心点并将两侧裁剪出来。

我在网络平台上找到了这个方法..但是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;
        }

请建议解决此问题的方法。

1 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

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;
}

这确实从中心裁剪。如果您想从底部/右侧裁剪,请使用var sourceRect = new Rectangle(0, 0, size, size);