WebImage裁剪成正方形

7

有没有人知道如何使用新的ASP.Net MVC 3 Html Helper WebImage将上传的文件裁剪成一个正方形。如果可能的话,我希望它居中。我已经花了几个小时试图解决这个问题...非常感谢您的帮助!

情景很简单,用户可以上传一张图片,然后将该图片调整大小为正方形,以便稍后在网站上用作缩略图。


这里有一些不错的例子 - http://weblogs.asp.net/gunnarpeipman/archive/2010/10/15/asp-net-mvc-3-beta-simple-image-manipulations-using-webimage-helper.aspx - Dan Atkinson
@Dan Atkinson - 是的,我看过那些例子,但我的问题是裁剪成正方形(并尝试居中)。 - B Z
3个回答

14

这对我起作用了,希望能为其他人节省一些时间...!

private static void CropImage (HttpPostedFileBase sourceImage) {
  var newImage = new WebImage(sourceImage.InputStream);

  var width = newImage.Width;
  var height = newImage.Height;

  if (width > height) {
    var leftRightCrop = (width - height) / 2;
    newImage.Crop(0, leftRightCrop, 0, leftRightCrop);
  }
  else if (height > width) {
    var topBottomCrop = (height - width) / 2;
    newImage.Crop(topBottomCrop, 0, topBottomCrop, 0);
  }

  //do something with cropped image...
  //newImage.GetBytes();
}

3
这里有一个小函数,可以从中心裁剪图片,但保持所需的比例。我用它来裁剪图库等图片。
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;
    }

3
我建议使用 Jquery图像裁剪插件。因为我认为自动裁剪正方形不好,因为你可能会剪掉图片的主要部分,例如如果是用户照片,你可能会裁剪他的头部。 图像裁剪插件很容易使用。用户只需选择要用作预览的区域。在服务器端,您将接收起点坐标和宽度/高度。对于服务器端的图像调整大小/裁剪,我使用 image magick。这里有.net下image magick的封装器。但要注意封装器仅支持32位。我为我的需要开发了自己的ImageMagick封装器。但我相信可以用.net轻松完成这个任务。
如果您仍然认为自动裁剪是您所需要的,请建议裁剪图像的最大中心正方形,然后调整大小到所需大小。
希望这有所帮助。
P.S. 我不知道但我认为这样的任务不能使用mvc WebImage来完成。

谢谢,我已经研究了jcrop,但我正在尝试使其尽可能无缝。我知道裁剪可能会导致一些意外的裁剪,但如果居中,它将大多数时候有效。 - B Z

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接