Thursday, 30 May 2013

Asp.net Mvc Image Helpers (Part 2)

Image helper with server side image re-size

In this second part we will continue on from part 1 and add a second option to our image controller that enables us to have the server re-size the image before sending it to the client.

First you need to install Image Resizer http://imageresizing.net/ through nuget, (Tools->Manage Nuget Packages), by searching "imageresizer". We will be using this package to re size the images.

Once the image resizer is installed in your mvc project we can add a new method to the Image Controller.

 public ActionResult ImageResize(string image, int width, int height)  
 {  
   var imagesPath = Server.MapPath("/Images");  
   var imageLocation = Path.Combine(imagesPath, image);  
   
   var settings = new ResizeSettings  
   {  
     Format = "jpg",  
     Mode = FitMode.Stretch,  
     Width = width,  
     Height = height,  
     Scale = ScaleMode.Both  
   };  
   
   var outStream = new MemoryStream();  
   ImageBuilder.Current.Build(System.IO.File.ReadAllBytes(imageLocation), outStream, settings);  
   var resizedImage = outStream.ToArray();  
   
   return File(resizedImage, "image/jpeg");  
 }  

In this we map the path as before and then re-size the image and pass it in to a memory stream so we can return the image to the client. There are plenty of options for image resizer see this page for more.

Next we need to add an overload to our html helper extension that allows us to specify image dimensions.

 public static MvcHtmlString Image(this HtmlHelper helper, string image, string alternate, int width, int height)  
 {  
   var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);  
   var url = urlHelper.Action("ImageResize", "Image", new {image, width, height});  
   
   var builder = new TagBuilder("img");

   builder.MergeAttribute("src", url);
   builder.MergeAttribute("alt", alternate);

   return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)); 
 }  

As before this uses a URL helper to generate the URL then generates a img tag using a Tag Builder before returning it as a MvcHtmlString.

To use this in razor just type:
 @Html.Image("test.jpg", "Example Image", 50, 50)  


In the next part of the series we will look at setting up an image helper that uses jQuery lazy load to load the images.

Links
Source Code

Part 1

No comments:

Post a Comment