神刀安全网

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.

using System.Collections.Generic;   namespace EFOperation.Models   {       public class ProfileViewModel       {           public string ProfileImage           {               get;               set;           }           public FileInfo[] FileInfoes           {               get;               set;           }       }   }   

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.

using EFOperation.Models;   using ImageResizer;   using System.IO;   using System.Web;   using System.Web.Mvc;   namespace EFOperation.Controllers   {       public class ProfileController: Controller       {           [HttpGet]           public ActionResult Index()           {               ProfileViewModel model = newProfileViewModel();               model.FileInfoes = newDirectoryInfo(Server.MapPath("~/images")).GetFiles();               return View(model);           }       }   }   

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.

@model EFOperation.Models.ProfileViewModel      <div class="row">       <div class="col-lg-6">           @using (Html.BeginForm("Index", "Profile", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form" }))           {                  <h4>Upload Image</h4>               <hr/>               <div class="form-group">                   @Html.LabelFor(m =>m.ProfileImage, new { @class = "col-md-2 control-label" })                          <div class="col-md-10">                           <input type="file"name="profileFile"id="profileFile"/>                       </div>               </div>               <div class="form-group">                   <div class="col-lg-4">                       <a href="#"class="thumbnail">                           <img id="uploading"src=""alt="uploading image">                           </a>                       </div>                   </div>                   <div class="form-group">                       <div class="col-md-offset-2 col-md-10">                           <input type="submit"class="btnbtn-default" value="Submit"/>                       </div>                   </div>           }          </div>           <div class="col-lg-6">               <h4>Uploaded Images</h4>               <hr/>               <div class="row">                   @foreach (var image inModel.FileInfoes)                   {                          <div class="col-lg-3">                           <img src="~/images/@image.Name"alt="@image.Name"class="img-circle">                           </div>                   }                      </div>               </div>           </div>      @section Scripts{       @Scripts.Render("~/Scripts/profile-index.js")   }   

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.

(function($)   {       function PersonDetail()       {           var $this = this;           function intialize()           {               $("#PersonId").change(function()               {                   var address = $("#addresses");                   address.html('');                   $.get("PersonAddressList",                   {                       id: $(this).val()                   }, function(data)                   {                       address.html(data);                   })               });           }           $this.init = function()           {               intialize();           }       }       $(function()       {           var self = newPersonDetail();           self.init();       })   })(jQuery)   

Now create post action to post the above form so that image can upload in directory. The following code snippet for same.

[HttpPost]   public ActionResult Index(HttpPostedFileBaseprofileFile)   {       if (profileFile != null)       {           string pic = System.IO.Path.GetFileName(profileFile.FileName);           string path = System.IO.Path.Combine(Server.MapPath("~/images"), pic);           profileFile.SaveAs(path);       }       return RedirectToAction("Index");   }   

Now run the application and result shown as per figure 1.

Image Resize In ASP.NET MVC Using Image Resizer

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.

Image Resize In ASP.NET MVC Using Image Resizer

Figure 2:Manage NuGet Packages window

The following is a basic typical configuration in web.config file for this package.

<configSections>      <sectionname="resizer"type="ImageResizer.ResizerSection,ImageResizer"requirePermission="false" />   </configSections>      <modules>      <removename="FormsAuthenticationModule" />      <addname="ImageResizingModule"type="ImageResizer.InterceptModule"/>   </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. 

<div class="col-lg-6">       <h4>Uploaded Images</h4>       <hr/>       <div class="row">           @foreach (var image inModel.FileInfoes) {               <div class="col-lg-3">                   <img src="~/images/@image.Name?w=160&h=100" alt="@image.Name" class="img-circle">               </div>           }       </div>   </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.

Image Resize In ASP.NET MVC Using Image Resizer

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.

[HttpPost]   public ActionResult Index(HttpPostedFileBaseprofileFile)   {       if (profileFile != null)       {           string pic = System.IO.Path.GetFileName(profileFile.FileName);           string path = System.IO.Path.Combine(Server.MapPath("~/images"), pic);           profileFile.SaveAs(path);           ResizeSettings resizeSetting = new ResizeSettings           {               Width = 150,                   Height = 100,                   Format = "png"           };           ImageBuilder.Current.Build(path, path, resizeSetting);       }       return RedirectToAction("Index");   }   

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:

new ResizeSettings("maxwidth=100&maxheight=100");   //or   new ResizeSettings(Request.QueryString);   //or   var r = newResizeSettings();   r.MaxWidth = 100;   r.MaxHeight = 100;   

Now run the application and upload an image as in the following figure 4.

Image Resize In ASP.NET MVC Using Image Resizer

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

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Image Resize In ASP.NET MVC Using Image Resizer

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址