Does anyone know how to use the new ASP.Net MVC 3 Html Helper WebImage to crop an uploaded file into a square. I would like to have it centered if possible. I've been banging my head for the last few hours trying to figure this out...any help is appreciated!
The scenario is pretty simple, user can upload an image, the image will then be resized to a square to be used later as a thumbnail in the site.
This worked for me, hope saves some time for others...!
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();
}
I suggest to use Jquery image crop plugin. Because i think not good to crop square automatically because you can remove main part of image, for example if it user photo you can crop his head.
Image crop plugin is easy to use. User just select are that he want to use as preview. At the server side you recive start point coordinates and width/height. For image resize/crop at server side i use image magick. There is wrapper for image magick at .net. Also be care with wrapper because it 32 bit only. I've developed for my needs own wrapper for image magick. But i belive that it can be easy done with .net.
If you still think that autocropping is what you need, i suggest to crop max center squere of image and than recize to size that you want.
Hope this help.
P.S. I don't know but i suppose that such task can't be done using mvc WebImage.
here is a little function that crops image from the center but keeping wanted ratio. I use it for cropping images for galleries and such.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With