Image Resize In ASP.NET MVC Using Image Resizer

Introduction

We have other approaches to resize an image in .NET such as GDI+, WPF, WCI and WebImage method. We implement these approaches using own custom code to resize an image. So, we use third party ‘ImageResizer’ nuget package with managed API to resize an image. It provides on demand image resizing as well.It has a very simple (and powerful) URL API.Thousands of popular websites rely on ImageResizer; some with millions of pageviews each day, like Sierra Trading Post, MSN, and eBay.

What is ImageResizer

  1. It is an IIS/ASP.NET HttpModule & image server. On-demand image manipulation, delivery, and optimization - with low latency - makes responsive images easy.

  2. As it’s open source so you can download from Git. The official repository for ImageResizer.

  3. An image processing library optimized and secured for server-side use.

Getting Started

We create an MVC application in which we upload image from view and shows those images. First and Foremost we create a view model ProfileViewModel as per following code snippet which used to pass images data of a directory from controller to strongly typed view.

  1. using System.Collections.Generic;    
  2. namespace EFOperation.Models    
  3. {    
  4.     public class ProfileViewModel    
  5.     {    
  6.         public string ProfileImage    
  7.         {    
  8.             get;    
  9.             set;    
  10.         }    
  11.         public FileInfo[] FileInfoes    
  12.         {    
  13.             get;    
  14.             set;    
  15.         }    
  16.     }    
  17. }    
Now we create a controller that has an action method of GET request type which renders view with image data as per following code snippet. 
  1. using EFOperation.Models;    
  2. using ImageResizer;    
  3. using System.IO;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  6. namespace EFOperation.Controllers    
  7. {    
  8.     public class ProfileController: Controller    
  9.     {    
  10.         [HttpGet]    
  11.         public ActionResult Index()    
  12.         {    
  13.             ProfileViewModel model = newProfileViewModel();    
  14.             model.FileInfoes = newDirectoryInfo(Server.MapPath("~/images")).GetFiles();    
  15.             return View(model);    
  16.         }    
  17.     }    
  18. }    
 
We create view for above action as per following code snippet in which we have a form to upload an image and show images listing from a directory those have been uploaded.
  1. @model EFOperation.Models.ProfileViewModel    
  2.     
  3. <div class="row">    
  4.     <div class="col-lg-6">    
  5.         @using (Html.BeginForm("Index", "Profile", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal"role = "form" }))    
  6.         {    
  7.     
  8.             <h4>Upload Image</h4>    
  9.             <hr/>    
  10.             <div class="form-group">    
  11.                 @Html.LabelFor(m =>m.ProfileImage, new { @class = "col-md-2 control-label" })    
  12.     
  13.                     <div class="col-md-10">    
  14.                         <input type="file"name="profileFile"id="profileFile"/>    
  15.                     </div>    
  16.             </div>    
  17.             <div class="form-group">    
  18.                 <div class="col-lg-4">    
  19.                     <a href="#"class="thumbnail">    
  20.                         <img id="uploading"src=""alt="uploading image">    
  21.                         </a>    
  22.                     </div>    
  23.                 </div>    
  24.                 <div class="form-group">    
  25.                     <div class="col-md-offset-2 col-md-10">    
  26.                         <input type="submit"class="btnbtn-default" value="Submit"/>    
  27.                     </div>    
  28.                 </div>    
  29.         }    
  30.     
  31.     </div>    
  32.         <div class="col-lg-6">    
  33.             <h4>Uploaded Images</h4>    
  34.             <hr/>    
  35.             <div class="row">    
  36.                 @foreach (var image inModel.FileInfoes)    
  37.                 {    
  38.     
  39.                     <div class="col-lg-3">    
  40.                         <img src="~/images/@image.Name"alt="@image.Name"class="img-circle">    
  41.                         </div>    
  42.                 }    
  43.     
  44.                 </div>    
  45.             </div>    
  46.         </div>    
  47.     
  48. @section Scripts{    
  49.     @Scripts.Render("~/Scripts/profile-index.js")    
  50. }    
 
Just we write JavaScript function so that an upload image may be shown at a time of image selected from file input type as per following code snippet.
  1. (function ($) {  
  2.   
  3.     function ProfileIndex() {  
  4.         var $this = this;  
  5.   
  6.         function intialize() {  
  7.             $("#profileFile").change(function () {  
  8.                 readURL(this);  
  9.             });  
  10.         }  
  11.   
  12.         function readURL(input) {  
  13.             if (input.files && input.files[0]) {  
  14.                 var reader = new FileReader();  
  15.   
  16.                 reader.onload = function (e) {  
  17.                     $('#uploading').attr('src', e.target.result);  
  18.                 }  
  19.                 reader.readAsDataURL(input.files[0]);  
  20.             }  
  21.         }  
  22.   
  23.         $this.init = function () {  
  24.             intialize();  
  25.         }  
  26.     }  
  27.   
  28.     $(function () {  
  29.         var self = new ProfileIndex();  
  30.         self.init();  
  31.     })  
  32.   
  33. })(jQuery)  
 
Now create post action to post the above form so that image can upload in directory. The following code snippet for same.
  1. [HttpPost]    
  2. public ActionResult Index(HttpPostedFileBaseprofileFile)    
  3. {    
  4.     if (profileFile != null)    
  5.     {    
  6.         string pic = System.IO.Path.GetFileName(profileFile.FileName);    
  7.         string path = System.IO.Path.Combine(Server.MapPath("~/images"), pic);    
  8.         profileFile.SaveAs(path);    
  9.     }    
  10.     return RedirectToAction("Index");    
  11. }    
Now run the application and result shown as per figure 1.

Output of Application
Figure 1: Output of Application

As per figure 1, we see that uploaded images are not showing in appropriate size so that those can fit in UI that’s why we resize an image. We have two options to fix this image UI issue one is image resize at a time of load/render on UI and another is resize image at a time of upload. Both options can be implemented by ‘ImageResizer’ plugin that’s why we install this nugget package.

On Demand Image Processing

As this package provides two options so we choose first on demand image processing option.We install ‘ImageResizer’ nuget package in our MVC application using the Manage NuGet Packages window as shown figure 2 and click on install button. The installation updates both packages.config and Web.config configuration files.

Manage NuGet Packages window
Figure 2: Manage NuGet Packages window

The following is a basic typical configuration in web.config file for this package.
  1. <configSections>     
  2.    <sectionnamesectionname="resizer"type="ImageResizer.ResizerSection,ImageResizer"requirePermission="false" />    
  3. </configSections>    
  4.     
  5. <modules>    
  6.    <removenameremovename="FormsAuthenticationModule" />    
  7.    <addnameaddname="ImageResizingModule"type="ImageResizer.InterceptModule"/>    
  8. </modules>    
 It is the set up and configuration part of the package. We do change on image listing part of the view to get images of appropriate size. We pass height and width as a query string to image URL and response image do processing based on pass parameters. The following snippet is updated fragment in the above view code. 
  1. <div class="col-lg-6">    
  2.     <h4>Uploaded Images</h4>    
  3.     <hr/>    
  4.     <div class="row">    
  5.         @foreach (var image inModel.FileInfoes) {    
  6.             <div class="col-lg-3">    
  7.                 <img src="~/images/@image.Name?w=160&h=100" alt="@image.Name" class="img-circle">    
  8.             </div>    
  9.         }    
  10.     </div>    
  11. </div>    
 
We passed width and height as parameters in above code snippet in image URL on view that resizes image at a time of response or processing from server so little code improves performance of application in respect to image loading. The result shown as in the following figure 3.

Output for on demand image processing
Figure 3: Output for on demand image processing

Image Resize by API

This part of article explains the second option in which image resizes at a time of upload using package API. We need to redefine POST action method in which image resize in 150X100 using resize API methods. The following code snippet is POST action in Profile controller.
  1. [HttpPost]    
  2. public ActionResult Index(HttpPostedFileBaseprofileFile)    
  3. {    
  4.     if (profileFile != null)    
  5.     {    
  6.         string pic = System.IO.Path.GetFileName(profileFile.FileName);    
  7.         string path = System.IO.Path.Combine(Server.MapPath("~/images"), pic);    
  8.         profileFile.SaveAs(path);    
  9.         ResizeSettings resizeSetting = new ResizeSettings    
  10.         {    
  11.             Width = 150,    
  12.                 Height = 100,    
  13.                 Format = "png"    
  14.         };    
  15.         ImageBuilder.Current.Build(path, path, resizeSetting);    
  16.     }    
  17.     return RedirectToAction("Index");    
  18. }    
 
In the above code, we upload an image and resize uploaded image using managed API. It is done by its Build method which takes three parameters. First two parameters represent image source and destination.

The image/object source may be a physical path (C:..), an app-relative virtual path (~/folder/image.jpg), an Image, Bitmap, Stream, VirtualFile, or HttpPostedFile instance.

The image/object destination may be a Stream instance, a physical path, or an app-relative virtual path.

Apart from above imageResizeSettings in POST action method, there is a friendly wrapper for a query string which provides named properties as well as the regular NameValueCollection interface.You can create as per following code snippet:
  1. new ResizeSettings("maxwidth=100&maxheight=100");    
  2. //or    
  3. new ResizeSettings(Request.QueryString);    
  4. //or    
  5. var r = newResizeSettings();    
  6. r.MaxWidth = 100;    
  7. r.MaxHeight = 100;    
 
Now run the application and upload an image as in the following figure 4.

Uploading image resize output
Figure 4: Uploading image resize output

It’s a simplest way to reduce image size and improves image loading performance. Most of code is single line code to implement API so it’s easy and simple to integrate in application.

An ASP.NET MVC helpful utility articles collection here: ASP.NET MVC CookBook 


Similar Articles