简体   繁体   中英

Change image size with C# in MVC3?

[HttpPost]
public ActionResult AddImage(Image model)
{
   if (model.ImageData != null && model.ImageData.ContentLength > 0)
   {
      var fileName = Path.GetFileName(model.ImageData.FileName);
      var pathBig = Path.Combine(Server.MapPath("~/UploadedImages"), fileName);
      var pathSmall = Path.Combine(Server.MapPath("~/UploadedImages"), "small_" + fileName);


      // --> How to change image size to big(800 x 600)
     //      and small (100x80) and save them?

      model.ImageData.SaveAs(pathBig);
      model.ImageData.SaveAs(pathSmall);
   }
}

How do I change the image size to big(800 x 600) to small (100x80) and save them?

You could try this library: http://nuget.org/packages/ImageResizer

It does support asp.net-mvc: http://imageresizing.net/

Or you could get a pure C# lib and use it on your app. See these posts:
Resize an Image C#
https://stackoverflow.com/a/2861813/368070

And this snippet I found : http://snippets.dzone.com/posts/show/4336

The simplest way of doing it from the framework methods itself will be to use the DrawImage() method of the Graphics Class.

The example code could be like:

//For first scale
Bitmap bmp = new Bitmap(800, 600);
Graphics gf = Graphics.FromImage(bmp);
Image userpic = Image.FromStream(/*pass here the image byte stream*/)
gf.DrawImage(userpic, new Rectangle(0,0,800,600))
gf.Save(/* the save path */);

//For second scale
Bitmap bmp = new Bitmap(100, 80);
Graphics gf = Graphics.FromImage(bmp);
Image userpic = Image.FromStream(/*pass here the image byte stream*/)
gf.DrawImage(userpic, new Rectangle(0,0,100,80))
gf.Save(/* the save path */);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM