Resize uploaded image in MVC 6

纵然是瞬间 提交于 2019-12-06 00:39:13

问题


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));
     }

回答1:


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)



来源:https://stackoverflow.com/questions/31901860/resize-uploaded-image-in-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!