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

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)

链接地址: http://www.djcxy.com/p/87350.html

上一篇: 如何使用firefox开发工具清除或删除浏览器会话

下一篇: 在MVC 6中调整上传的图像大小