在MVC 6中调整上传的图像大小

7

如何在MVC 6中调整上传图像的大小?我希望存储多个变体的图像(例如小型、大型等),以便稍后选择要显示的图像。

这是我的操作代码。

    [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个回答

4
我建议使用Image Processor库。 http://imageprocessor.org/imageprocessor/ 然后你只需要按照以下方式进行操作:
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);
}

file.Value是您上传的文件(流)(我不知道在MVC中是什么,这是我在Nancy项目中使用的代码)。


谢谢!正是我所需要的! - Sergey Kandaurov
@Phill 很棒的链接,谢谢,这是我找到的唯一关于vNext图像的东西。但是“new Size”是System.Drawing的一部分吗? - Alex
@voo 目前的 Nuget 仍需要 System.Drawing,但 V2 的 API 将更改以删除该约束。https://github.com/JimBobSquarePants/ImageProcessor#api-changes - Phill
1
ImageProcessor库的问题在于它需要.NET完整框架,但如果你想使用.NET Core,目前我还没有找到任何解决方案。 - jsDevia
@elhampour 新的 API 已经在 .NetCore 上运行,不过仍然需要继续改进。 - James South

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接