Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize uploaded image in MVC 6

What is the best way to resize an uploaded image in MVC 6? I'd like to store multiple variants of an image (such as small, large, etc.) to be able to choose which to display later.

Here's 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));
     }
like image 710
Sergey Kandaurov Avatar asked Aug 09 '15 07:08

Sergey Kandaurov


1 Answers

I would suggest using Image Processor library.

http://imageprocessor.org/imageprocessor/

Then you can just do something along the lines of:

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 (the stream) (I don't know what it is in MVC, this is code I use in a Nancy project)

like image 164
Phill Avatar answered Oct 21 '22 04:10

Phill