加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:06:03 所属栏目:asp.Net 来源:网络整理
导读:在MVC 6中调整上传图像大小的最佳方法是什么?我想存储图像的多个变体(例如小,大等),以便能够选择稍后显示的内容. 这是我的行动代码. [HttpPost] public async TaskIActionResult UploadPhoto() { if (Request.Form.Files.Count != 1) return new HttpStatus
在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));
     }

解决方法

我建议使用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项目中使用的代码)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读