Return thumbnail image from ASP.NET MVC action method

Sheonarayan
Posted by Sheonarayan under ASP.NET MVC category on | Points: 40 | Views : 3941
To return thumbnail image from ASP.NET MVC action method, Follow below approach.

Controller code

public FileResult GetThumbnail(string fileName)
{
var path = Server.MapPath(fileName);
var stream = new MemoryStream();
var exteName = Path.GetExtension(path);

using (Image image = Image.FromFile(path))
{
using (Image thumb = image.GetThumbnailImage(120, 120, () => false, IntPtr.Zero))
{
thumb.Save(stream, ImageFormat.Png);
}
}
return File(stream.ToArray(), "image/" + exteName.Substring(1));
}

Above code will generate a thumbnail image of 120*120 based the file name passed.
View code

<img class="img-thumbnail" src="/Home/GetThumbnail/?fileName=/images/asb.jpg" alt="" />

When the <img> tag renders it calls /Home/GetThumbnail action method that generates the thumbnail from the fileName value and return an stream of array that shows the image of 120*120.

Comments or Responses

Posted by: Amatya on: 12/8/2016 Level:Silver | Status: [Member] | Points: 10
Nice 1 sir

Login to post response