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

前端之家收集整理的这篇文章主要介绍了在MVC 6中调整上传的图像大小前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在MVC 6中调整上传图像大小的最佳方法是什么?我想存储图像的多个变体(例如小,大等),以便能够选择稍后显示内容.

这是我的行动代码.

  1. [HttpPost]
  2. public async Task<IActionResult> UploadPhoto()
  3. {
  4. if (Request.Form.Files.Count != 1)
  5. return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
  6.  
  7. IFormFile file = Request.Form.Files[0];
  8.  
  9. // calculate hash
  10. var sha = System.Security.Cryptography.SHA256.Create();
  11. byte[] hash = sha.ComputeHash(file.OpenReadStream());
  12.  
  13. // calculate name and patch where to store the file
  14. string extention = ExtentionFromContentType(file.ContentType);
  15. if (String.IsNullOrEmpty(extention))
  16. return HttpBadRequest("File type not supported");
  17.  
  18. string name = WebEncoders.Base64UrlEncode(hash) + extention;
  19. string path = "uploads/photo/" + name;
  20.  
  21. // save the file
  22. await file.SaveAsAsync(this.HostingEnvironment.MapPath(path));
  23. }

解决方法

我建议使用Image Processor库.

http://imageprocessor.org/imageprocessor/

然后你可以做一些事情:

  1. using (var imageFactory = new ImageFactory())
  2. using (var fileStream = new FileStream(path))
  3. {
  4. file.Value.Seek(0,SeekOrigin.Begin);
  5.  
  6. imageFactory.FixGamma = false;
  7. imageFactory.Load(file.Value)
  8. .Resize(new ResizeLayer(new Size(264,176)))
  9. .Format(new JpegFormat
  10. {
  11. Quality = 100
  12. })
  13. .Quality(100)
  14. .Save(fileStream);
  15. }

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

猜你在找的asp.Net相关文章