Wednesday 20 April 2016

How to convert large image to Small image in MVC

View


@{


ViewBag.Title = "Index";






}


 


 


@using (Html.BeginForm("Post", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))








{


<table align="center">


<tr><td><input type="file" id="file" name="file" /></td></tr>


<tr><td><input type="submit" value="Upload" /></td></tr>


</table>





}


Controller


using System;


using System.Collections.Generic;


using System.Drawing;


using System.Drawing.Drawing2D;


using System.IO;


using System.Linq;


using System.Web;


using System.Web.Mvc;


namespace MvcApplication13.Controllers






{


public class HomeController : Controller





{





public ActionResult Index()






{


return View();






}


[HttpPost]

public ActionResult Post(HttpPostedFileBase file)






{


if (file != null)






{


string pic = System.IO.Path.GetFileName(file.FileName);

string path = System.IO.Path.Combine(Server.MapPath("~/Image"), pic);

string targetPath = Server.MapPath("~/Image/" +"small"+ pic);

Stream strm = file.InputStream;

var targetFile = targetPath;






ConvertToSmallImage(0.05, strm, targetFile);


file.SaveAs(path);


}


return RedirectToAction("Index");






}


private void ConvertToSmallImage(double scaleFactor, Stream sourcePath, string targetPath)






{


var image = System.Drawing.Image.FromStream(sourcePath);

var newWidth = (int)(image.Width * scaleFactor);

var newHeight = (int)(image.Height * scaleFactor);

var thumbnailImg = new Bitmap(newWidth, newHeight);

var thumbGraph = Graphics.FromImage(thumbnailImg);

thumbGraph.CompositingQuality = CompositingQuality.HighQuality;

thumbGraph.SmoothingMode = SmoothingMode.HighQuality;

thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);






thumbGraph.DrawImage(image, imageRectangle);


thumbnailImg.Save(targetPath, image.RawFormat);


}


}


}


No comments:

Post a Comment