WebImage裁剪到正方形

有谁知道如何使用新的ASP.Net MVC 3 Html Helper WebImage将上传的文件裁剪成正方形。 如果可能的话,我想让它居中。 在过去的几个小时里,我一直在试图解决这个问题……任何帮助都表示赞赏!

场景非常简单,用户可以上传图像,然后将图像调整为正方形,以便稍后用作网站中的缩略图。

这对我有用,希望为别人节省一些时间……!

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

我建议使用Jquery图像裁剪插件 。 因为我认为不能自动裁剪方形,因为你可以删除图像的主要部分,例如,如果用户照片你可以裁剪他的头。

图像裁剪插件易于使用。 用户只需选择他想要用作预览。 在服务器端,您可以查看起点坐标和宽度/高度。 对于服务器端的图像resize/裁剪,我使用image magick 。 在.net上有图像魔法的包装 。 还要小心包装,因为它只有32位。 我为我的需求开发了自己的图像魔法包装器。 但我相信用.net可以轻松完成。

如果您仍然认为自动裁剪是您所需要的,我建议裁剪图像的最大中心位置,然后重新调整到您想要的大小。

希望这有帮助。

PS我不知道,但我认为使用mvc WebImage无法完成此类任务。

这是一个小function,从中心裁剪图像,但保持通缉比率。 我用它来为画廊等裁剪图像。

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