1011 1110
1011 1110

Reputation: 781

Restrict Resolution on a passed in image

Passing an image from a form to my controller post. It's being caught as an HttpPostedFileBase. There's some validation I would like to do to the image though.

I would like to enforce a restriction on the resolution size before it saves the file, but since its a HttpPostedFileBase I can't. Is there a way to convert this into an Image property or any other way around it.

Here is my controller:

        [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);
        } 

Upvotes: 2

Views: 361

Answers (1)

dom
dom

Reputation: 6832

You can simply convert your System.Web.HttpPostedFileBase to a System.Drawing.Image and validate the Width and Height properties (I assume this is what you mean by resolution).

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

That should do it. Don't forget to include a reference to System.Drawing.

Upvotes: 4

Related Questions