Resize an uploaded image in MVC 6

What is the best way to resize an uploaded image in MVC 6? I would like to save several options for the image (for example, small, large, etc.), in order to be able to choose what will be displayed later.

Here is my code for the action.

[HttpPost] public async Task<IActionResult> UploadPhoto() { if (Request.Form.Files.Count != 1) return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest); IFormFile file = Request.Form.Files[0]; // calculate hash var sha = System.Security.Cryptography.SHA256.Create(); byte[] hash = sha.ComputeHash(file.OpenReadStream()); // calculate name and patch where to store the file string extention = ExtentionFromContentType(file.ContentType); if (String.IsNullOrEmpty(extention)) return HttpBadRequest("File type not supported"); string name = WebEncoders.Base64UrlEncode(hash) + extention; string path = "uploads/photo/" + name; // save the file await file.SaveAsAsync(this.HostingEnvironment.MapPath(path)); } 
+7
image asp.net-core-mvc
source share
1 answer

I would suggest using the Image Processor library.

http://imageprocessor.org/imageprocessor/

Then you can just do something line by line:

 using (var imageFactory = new ImageFactory()) using (var fileStream = new FileStream(path)) { file.Value.Seek(0, SeekOrigin.Begin); imageFactory.FixGamma = false; imageFactory.Load(file.Value) .Resize(new ResizeLayer(new Size(264, 176))) .Format(new JpegFormat { Quality = 100 }) .Quality(100) .Save(fileStream); } 

Where file.Value is your file that was uploaded (stream) (I don't know what it is in MVC, this is the code I use in a Nancy project)

+4
source share

All Articles