限制传入图像的分辨率

时间:2014-07-09 16:57:47

标签: c# image asp.net-mvc-5 converter

将图像从表单传递到控制器帖子。它被HttpPostedFileBase抓住了。我想对图像进行一些验证。

我想在保存文件之前对分辨率大小强制执行限制,但由于它是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);
        } 

1 个答案:

答案 0 :(得分:3)

您只需将System.Web.HttpPostedFileBase转换为System.Drawing.Image并验证WidthHeight属性(我认为这就是解析的含义)。

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

应该这样做。不要忘记包含对System.Drawing的引用。