2015-08-09 65 views
7

在MVC 6中調整上傳圖像的最佳方式是什麼?我想存儲圖像的多個變體(如小,大等),以便能夠選擇稍後顯示的圖像。在MVC 6中調整上傳圖像的大小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)); 
    } 

回答

4

我會建議使用圖像處理器庫。

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 ,這是我在南希項目中使用的代碼)

+0

謝謝!正是我需要的! –

+0

@Phill偉大的鏈接,謝謝,我發現了唯一的vNext圖像。但是「新大小」是System.Drawing部分嗎? – Alex

+0

@voo當前的Nuget仍然需要System.Drawing,但API正在改變V2來放棄這個約束。 https://github.com/JimBobSquarePants/ImageProcessor#api-changes – Phill