【问题标题】:Cropping a Bitmap to 1:1 Aspect Ratio [closed]将位图裁剪为 1:1 纵横比 [关闭]
【发布时间】:2016-04-02 00:56:32
【问题描述】:

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

当用户指定一个选项时,我需要一种从这些图像中裁剪出周围部分的方法,以便生成具有 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;
        }

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

【问题讨论】:

  • 有一个 DrawImage 重载需要一个源矩形。使用它来绘制合适的目标位图!
  • 您是否要求将图像矩形转换为正方形?
  • @IvanStoev 是的......有点
  • Here 是裁剪的示例,您可以根据需要进行调整..
  • @IvanStoev 当纵横比设置为 1:1 时,该方法会引发一些异常并导致进程崩溃。

标签: c# .net bitmap system.drawing


【解决方案1】:

你可以这样使用:

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

【讨论】:

  • 谢谢 :)......
  • 这刚刚解决了我的问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-07-19
  • 2013-08-31
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2020-03-14
相关资源
最近更新 更多