【问题标题】:Restrict Resolution on a passed in image限制传入图像的分辨率
【发布时间】:2014-08-30 19:52:43
【问题描述】:

将图像从表单传递到我的控制器帖子。它被捕获为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);
        } 

【问题讨论】:

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


    【解决方案1】:

    您可以简单地将System.Web.HttpPostedFileBase 转换为System.Drawing.Image 并验证Width 和Height 属性(我假设这就是您所说的分辨率)。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多