public ActionResult UploadImage(ImageModel model) { if (Request.Files.Count < 1 || Request.Files[0].ContentLength == 0) return new HttpStatusCodeResult(403); var files = new List<FilesStatus>(); var file = Request.Files[0]; if (file != null && !Regex.IsMatch(file.ContentType, "^image/")) { return new HttpStatusCodeResult(403); } try { // Get and add cropped image ImageFormat imageFormat = GetImageFormat(file); var croppedImageBytes = GetCroppedImage(model, file, imageFormat); string croppedImageName = string.Empty; if (croppedImageBytes != null) { croppedImageName = Constants.CroppedImagePrefix + file.FileName; Session.Add(croppedImageName, croppedImageBytes); } var originalImageBytes = new byte[file.ContentLength]; file.InputStream.Seek(0, SeekOrigin.Begin); file.InputStream.Read(originalImageBytes, 0, file.ContentLength); Session.Add(file.FileName, originalImageBytes); string thumbnailName; var thumbImg = GetThumbImage(croppedImageBytes ?? originalImageBytes, imageFormat, file, out thumbnailName); Session.Add(thumbnailName, thumbImg); files.Add(new FilesStatus { size = originalImageBytes.Length, name = file.FileName, url = Url.Action("Image", new { session = true, name = file.FileName + "/" }), thumbnail_url = Url.Action("Image", new { session = true, name = thumbnailName + "/" }), type = file.ContentType, cropped_image_name = croppedImageName, cropped_image_size = croppedImageBytes != null ? croppedImageBytes.Length : 0 }); } catch (Exception ex) { files.Add(new FilesStatus { name = file.FileName, error = ex.Message, }); } var json = _jsonSerializer.Serialize(new FilesWrapper { files = files }); return Json(json); }
private static byte[] GetCroppedImage(ImageModel model, HttpPostedFileBase file, ImageFormat imageFormat) { if (Math.Abs(model.CropX1 - model.CropX2) > 0 && Math.Abs(model.CropY1 - model.CropY2) > 0) { int width = Math.Abs(model.CropX2 - model.CropX1); int height = Math.Abs(model.CropY2 - model.CropY1); var cropRectangle = new Rectangle(model.CropX1, model.CropY1, width, height); byte[] croppedImage; using (var src = (Bitmap)System.Drawing.Image.FromStream(file.InputStream)) using (var target = new Bitmap(cropRectangle.Width, cropRectangle.Height)) { using (Graphics graphics = Graphics.FromImage(target)) { graphics.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRectangle, GraphicsUnit.Pixel); } using (var stream = new MemoryStream()) { target.Save(stream, imageFormat); croppedImage = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(croppedImage, 0, (int)stream.Length); } } return croppedImage; } return null; }