2014-07-09 32 views
1

將圖像從表單傳遞到我的控制器帖子。它被捕獲爲HttpPostedFileBase。雖然我想對圖像進行一些驗證。限制對傳入圖像的分辨率

我想在保存文件之前強制執行分辨率大小的限制,但是由於其不能。有沒有辦法將其轉換爲Image屬性或其他任何方式。

這裏是我的控制器:

 [HttpPost] 
     public ActionResult BannerEditorEdit([Bind(Include = "ID,title,subTitle,imgPath,startBanner")]HttpPostedFileBase photo, BannerEditor bannerEditor) 
     { 



      if (ModelState.IsValid) 
      { 
       if (photo != null) 
       { 
        string basePath = Server.MapPath("~/Content/Images"); 

        var supportedTypes = new[] { "jpg", "jpeg", "png", "PNG", "JPG", "JPEG" }; 

        var fileExt = System.IO.Path.GetExtension(photo.FileName).Substring(1); 

        if (!supportedTypes.Contains(fileExt)) 
        { 
         ModelState.AddModelError("photo", "Invalid type. Only the following types (jpg, jpeg, png) are supported."); 
         return View(); 
        } 
        photo.SaveAs(basePath+ "//" + photo.FileName); 

        bannerEditor.imgPath = ("/Content/Images/" + photo.FileName); 
       } 
       else 
       { 
        ModelState.AddModelError("photo", "Must supply a Banner imgage"); 

       } 
       db.Entry(bannerEditor).State = EntityState.Modified; 
       db.SaveChanges(); 
       return RedirectToAction("BannerEditorIndex"); 
      } 
      return View(bannerEditor); 
     } 

回答

3

你可以簡單地轉換您System.Web.HttpPostedFileBaseSystem.Drawing.Image和驗證WidthHeight屬性(我想這是你通過決議的意思)。

using (Image img = Image.FromStream(photo.InputStream)) 
{ 
    if (img.Width <= xxx && img.Height <= xxx) 
    { 
     // do stuff 
    } 
} 

這應該這樣做。不要忘記提及System.Drawing