有没有人知道如何使用新的ASP.Net MVC 3 Html Helper 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();
}
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;
}