Image Resize in ASP.NET MVC
This article is about resizing the image in ASP.NET MVC. There are many articles has been posted for image resizing in ASP.NET. This is a article combines the resizing options with ASP.NET MVC.
you can download the source code from the following location
http://www.meenakshisolutions.com/code/imageresize.zip
Steps involved in resizing the image are
ImageResizing Class - Implemented to handle the resizing mechanism and maintaining the scalefactor of the image.
ImageActionResult - Custom Action Result to make the response as image content type
MapRoute - Url Maping to accept width and height values
ImageController - Controller and Action part of the ASP.NET MVC
First is to Create to create ASP.NET MVC project named ImageResize in Visual Studio 2008. Next step is creating a class file which will handle image resize functionality. I am passing the image path as a parameter in the constructor.
I have created three Overloaded Resize method to resize the image.
First Overloaded method will handle the image resize by specifying width and height.
Second Overloaded method will handle the image resize by specifying the percentage of the original image to be resized.
The Third Overloaded Resize method is used to calculate the image width/height ratio and in turn call the GenerateResizedImage to resize the image.
GenerateResizedImage methods is used to get the resized image without the loss of quality.
Here is the complete class file named ImageEditing created in Models folder. I have Created Overloaded method named Resize.
Image.GetThumbnailImage result in poor resize quality. So i have gone for the custom resizing method which i have obtained from the following articles by Gunnar Peipman’s
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace ImageResize.Models
{
public class ImageEditing
{
private string _OriginalPath;
/// <summary>
/// Initializes a new instance of the ImageEditing class
/// </summary>
/// <param name="Path">To store image original path</param>
public ImageEditing(string Path)
{
this._OriginalPath = Path;
}
/// <summary>
/// To resize images to different sizes
/// </summary>
/// <param name="width">image width</param>
/// <param name="height">image height </param>
/// <returns>resized image</returns>
public Image Resize(int width, int height)
{
return this.Resize(width, height, System.Drawing.Image.FromFile(this._OriginalPath));
}
/// <summary>
/// To resize image with respect to given ratio.
/// </summary>
/// <param name="ratio">ratio of the image.</param>
/// <param name="path">source of the image.</param>
/// <returns>resized ratio of the image</returns>
public Image Resize(int ratio)
{
Image tempimage = System.Drawing.Image.FromFile(this._OriginalPath);
return this.Resize((int)(tempimage.Width * 0.01 * ratio), (int)(tempimage.Height * 0.01 * ratio), System.Drawing.Image.FromFile(this._OriginalPath));
}
/// <summary>
/// To resize images to different sizes
/// </summary>
/// <param name="width">Image width</param>
/// <param name="height">image width </param>
/// <param name="Path">path(url) of the image </param>
/// <returns>resized image</returns>
public Image Resize(int width, int height, string Path)
{
return this.Resize(width, height, System.Drawing.Image.FromFile(Path));
}
/// <summary>
/// To resize images to different sizes
/// </summary>
/// <param name="width">image width</param>
/// <param name="height">image height</param>
/// <param name="ImageInfo">image informations</param>
/// <returns>resized image</returns>
public Image Resize(int width, int height, Image ImageInfo)
{
decimal HeigthWidthRatio = (decimal)ImageInfo.Height / (decimal)ImageInfo.Width;
if (width > ImageInfo.Width)
{
width = ImageInfo.Width;
}
if ((decimal)ImageInfo.Width / width > (decimal)ImageInfo.Height / height)
{
height = (int)((decimal)width * HeigthWidthRatio);
}
else
{
width = (int)((decimal)height / HeigthWidthRatio);
}
return this.GenerateResizedImage(width, height, ImageInfo);
}
/// <summary>
/// To geneterate thumbnail image
/// </summary>
/// <param name="width">image width</param>
/// <param name="height"> image height</param>
/// <param name="Imageinfo"> image informations</param>
/// <returns>thumbnail image</returns>
private Image GenerateResizedImage(int width, int height, Image Imageinfo)
{
if (width <= 0 | height <= 0)
{
throw new Exception("Either width or heigth has invalid value");
}
try
{
System.Drawing.Image ThumbNail = new Bitmap(width, height, Imageinfo.PixelFormat);
Graphics Graphic = Graphics.FromImage(ThumbNail);
Graphic.CompositingQuality = CompositingQuality.HighQuality;
Graphic.SmoothingMode = SmoothingMode.HighQuality;
Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle Rectangle = new Rectangle(0, 0, width, height);
Graphic.DrawImage(Imageinfo, Rectangle);
return ThumbNail;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
Imageinfo.Dispose();
}
}
}
}
Next Step is create a custom ActionResult for handling image content type. I have created the folder named ActionResult and i created the ActionResult name ImageActionResult .
I am going to make the response content type to the browser as image/jpeg content type. This is achieved by overriding the ExecuteResult method of the ActionResult.
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;
using System.Drawing.Imaging;
using System.Drawing;
namespace ImageResize.ActionResults
{
/// <summary>
/// To save and retrieve image in different sizes.
/// </summary>
public class ImageActionResult : ActionResult
{
private Image _SourceImage;
/// <summary>
/// Gets or sets the image.
/// </summary>
/// <param name="SourceImage">resized image details</param>
public ImageActionResult(Image SourceImage)
{
this._SourceImage = SourceImage;
}
public override void ExecuteResult(ControllerContext context)
{
this.GenerateImage(context);
}
/// <summary>
/// save different size of image
/// </summary>
/// <param name="context"></param>
private void GenerateImage(ControllerContext context)
{
context.HttpContext.Response.ContentType = "image/jpeg";
this._SourceImage.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg);
this._SourceImage.Dispose();
}
}
}
Next step to MapRoute in the Global.asax.cs file. I made the default controller as Image and default action as VaryImageSize. Apart from this i have created two parameter values named width and height. The format of the Url to be handled will be like as shown
http://localhost:1230/Image/VaryImageSize/200/200
here the values of 200 refers to width and height of the image to be resized
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace ImageResize
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{width}/{height}",
new { controller = "Image", action = "VaryImageSize", width = "", height = ""});
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
Last Step to create Controller name ImageController and Action named VaryImageSize with the return type as ImageAction Result which make the response Content type as Image.
VaryImageASize Action accepts two parameter named width and height.
Here i am using static image named “sample.jpg” fro resizing which is located in the images folder. Any one can implement there own functionality to load the image.
The below image is the sample.jpg image i have used in this project
I haven’t done any input parameter validation for width and height.
I have written the code to display original size of the image when width and height is not given. sample url for this will be
http://localhost:1230/Image/VaryImageSize
For Percentage Options i used width parameter. If i enter the value for the width only and not for height then the code resize the image by assuming the width value as a percentage. sample url is given below
http://localhost:1230/Image/VaryImageSize/80
Here the 80 refers to the 80% of the original size to be resized
If there is any error throws then “noimage.jpg” is shown as the output image
This is the noimage.jpg file
This is the ImageController Class File.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using ImageResize.ActionResults;
using ImageResize.Models;
using System.Drawing;
namespace ImageResize.Controllers
{
public class ImageController : Controller
{
public ImageActionResult VaryImageSize(string width, string height)
{
Int16 WidthToResize;
Int16 HeightToResize;
string originalFilePath = AppDomain.CurrentDomain.BaseDirectory + "images/sample.jpg";
ImageEditing imgedit = new ImageEditing(originalFilePath);
Image resultimage;
try
{
if (width == string.Empty && height == string.Empty)
{
resultimage = imgedit.Resize(100);
}
else
{
Int16.TryParse(width, out WidthToResize);
Int16.TryParse(height, out HeightToResize);
if (WidthToResize <= 0)
{
throw new Exception();
}
if (HeightToResize <= 0)
{
resultimage = imgedit.Resize(WidthToResize);
}
else
{
resultimage = imgedit.Resize(WidthToResize, HeightToResize);
}
}
}
catch
{
resultimage = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "images/noimage.jpg");
}
return new ImageActionResult(resultimage);
}
}
}
Some of the Sample Url that shows the resized image content are
http://localhost:1230/Image/VaryImageSize/200/200 – Shows the image resized to 200 x 200
http://localhost:1230/Image/VaryImageSize/80 – Shows the resized image reduced by 80% of original image
http://localhost:1230/Image/VaryImageSize – Shows the original image
That’s the end of the article. Hope u can find the way to resize the image in ASP.NET MVC.
As this is my first article in the web your feedback and suggestion are welcome.

