Checking Images in MVC

Purpose:
Assess the format, width and height of the image, and then save it in my program.

Problem:
I don’t know how to use the HttpPostedFileBase file , and then send it to Image newImage = Image.FromFile(xxxx); without saving the image in my program.

  • Check
  • save image in my "App_Data"
 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Add(HttpPostedFileBase file) { if (file.ContentLength > 0) { Image newImage = Image.FromFile(xxxx); } return Index(); } 
+8
c # asp.net-mvc asp.net-mvc-2
source share
2 answers

You can do it something like the following snippet. Pay attention to the System.Drawing namespace link, you will need the Image.FromStream() method.

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Add(HttpPostedFileBase httpPostedFileBase) { using (System.Drawing.Image image = System.Drawing.Image.FromStream(httpPostedFileBase.InputStream, true, true)) { if (image.Width == 100 && image.Height == 100) { var file = @"D:\test.jpg"; image.Save(file); } } return View(); } 
+12
source share

HttpPostedFile has a stream property, which is the loaded data. Use this as with the Image.FromStream method to load an image.

I suggest you read the help on the HttpPostedFile here:

http://msdn.microsoft.com/en-us/library/SYSTEM.WEB.HTTPPOSTEDFILE(v=vs.100,d=lightweight).aspx

Simon

+2
source share

All Articles