Creating the thumbnail images on the fly with Asp.Net MVC

Creating the thumbnail images on the fly with Asp.Net MVC

 Asp.Net   
 

Posted: September 20, 2017. | By: mustafa

Asp.net mvc create a method to generate thumbnail on fly, using WebImage class that comes in System.Web.Helpers.WebImage. Adding caching will help to make it faster. Create a Thumbnail method passing filename as parameter. 

[OutputCache(Duration = 3600, VaryByParam = "filename")]
 public void Thumbnail(string filename)
 {
 // file is residing on Asp.Net Server.
 var path = Server.MapPath("/image/" + filename);
 
 new WebImage(path)
 .Resize(256, 256, false, true)
 .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage)
 .Write(); 
 }
 


Using .Write() method of WebImage class generate thumbnail image on fly which is directly sent to the browser.

In a view using the Razor syntax calling above method.

 

<img src="@Url.Action("Thumbnail", new { filename = filename })" width="256" height="256"/>

Now suppose you required to get the image from network using http url, As the image is not on a Asp.Net server we first need to download the image to resize.

[OutputCache(Duration = 3600, VaryByParam = "filename")]
 public void Thumbnail(string filename)
 {
 // download the file using http path available on network.
 var httpPath = "http://example.com/image/" + filename;
 
 new WebImage(DownloadItem(httpPath))
 .Resize(256, 256, false, true)
 .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage)
 .Write(); 
 }


Method to download the file from httpUrl.

public byte[] DownloadItem(string url)
 {
 WebClient myWebClient = new WebClient();
 byte[] myDataBuffer = myWebClient.DownloadData(url);
 return myDataBuffer;
 }

 


related posts

Back to top