<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Chidambara Jagannathan</title>
	<atom:link href="http://jaganeee.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jaganeee.wordpress.com</link>
	<description>You miss 100 percent of the shots you never take</description>
	<lastBuildDate>Fri, 26 Aug 2011 23:28:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='jaganeee.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Chidambara Jagannathan</title>
		<link>http://jaganeee.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://jaganeee.wordpress.com/osd.xml" title="Chidambara Jagannathan" />
	<atom:link rel='hub' href='http://jaganeee.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Image Resize in ASP.NET MVC</title>
		<link>http://jaganeee.wordpress.com/2010/02/10/image-resize-using-asp-net-mvc/</link>
		<comments>http://jaganeee.wordpress.com/2010/02/10/image-resize-using-asp-net-mvc/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 06:49:28 +0000</pubDate>
		<dc:creator>jaganeee</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://jaganeee.wordpress.com/?p=18</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaganeee.wordpress.com&amp;blog=3894309&amp;post=18&amp;subd=jaganeee&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This article is about resizing the image in <strong>ASP.NET MVC</strong>. There are many articles has been posted for image resizing in ASP.NET. This is a article combines the resizing options with  <strong>ASP.NET MVC</strong>.</p>
<p>you can download the source code from the following location<br />
<strong>http://www.meenakshisolutions.com/code/imageresize.zip</strong></p>
<p>Steps involved in resizing the image are</p>
<p><strong>ImageResizing Class</strong> -  Implemented to handle the resizing mechanism and maintaining the scalefactor of the image.</p>
<p><strong>ImageActionResult </strong>-  Custom Action Result to make the response as image content type</p>
<p><strong>MapRoute </strong>- Url Maping to accept width and height values</p>
<p><strong>ImageController </strong>-  Controller and Action part of the ASP.NET MVC</p>
<p>First is to Create to create ASP.NET MVC project named <strong> ImageResize </strong> 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. </p>
<p>I have created three Overloaded <strong> Resize </strong> method to resize the image.</p>
<p>First Overloaded method will handle the image resize by specifying width and height.</p>
<p>Second Overloaded method will handle the image resize by specifying the percentage of the original image to be resized.</p>
<p>The Third Overloaded Resize method is used to calculate the image width/height ratio and in turn call the GenerateResizedImage to resize the image.</p>
<p><strong>GenerateResizedImage </strong>methods is used to get the resized image without the loss of quality.</p>
<p>Here is the complete class file named <strong>ImageEditing</strong> created in Models folder. I have Created Overloaded method named <strong>Resize</strong>.</p>
<p>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 <a href="http://weblogs.asp.net/gunnarpeipman/archive/2009/04/02/resizing-images-without-loss-of-quality.aspx" target="_blank"><strong> Gunnar Peipman&#8217;s </strong></a></p>
<p><pre class="brush: csharp;">
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;

        /// &lt;summary&gt;
        /// Initializes a new instance of the ImageEditing class
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;Path&quot;&gt;To store image original path&lt;/param&gt;
        public ImageEditing(string Path)
        {
            this._OriginalPath = Path;
        }

        
        /// &lt;summary&gt;
        /// To resize images to different sizes
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;width&quot;&gt;image width&lt;/param&gt;
        /// &lt;param name=&quot;height&quot;&gt;image height &lt;/param&gt;
        /// &lt;returns&gt;resized image&lt;/returns&gt;
        public Image Resize(int width, int height)
        {
            return this.Resize(width, height, System.Drawing.Image.FromFile(this._OriginalPath));
        }

        /// &lt;summary&gt;
        /// To resize image with respect to given ratio.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ratio&quot;&gt;ratio of the image.&lt;/param&gt;
        /// &lt;param name=&quot;path&quot;&gt;source of the image.&lt;/param&gt;
        /// &lt;returns&gt;resized ratio of the image&lt;/returns&gt;
        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));
        }

        /// &lt;summary&gt;
        /// To resize images to different sizes
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;width&quot;&gt;Image width&lt;/param&gt;
        /// &lt;param name=&quot;height&quot;&gt;image width &lt;/param&gt;
        /// &lt;param name=&quot;Path&quot;&gt;path(url) of the image &lt;/param&gt;
        /// &lt;returns&gt;resized image&lt;/returns&gt;
        public Image Resize(int width, int height, string Path)
        {
            return this.Resize(width, height, System.Drawing.Image.FromFile(Path));
        }

        /// &lt;summary&gt;
        /// To resize images to different sizes
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;width&quot;&gt;image width&lt;/param&gt;
        /// &lt;param name=&quot;height&quot;&gt;image height&lt;/param&gt;
        /// &lt;param name=&quot;ImageInfo&quot;&gt;image informations&lt;/param&gt;
        /// &lt;returns&gt;resized image&lt;/returns&gt;
        public Image Resize(int width, int height, Image ImageInfo)
        {
            decimal HeigthWidthRatio = (decimal)ImageInfo.Height / (decimal)ImageInfo.Width;

            if (width &gt; ImageInfo.Width)
            {
                width = ImageInfo.Width;
            }

            if ((decimal)ImageInfo.Width / width &gt; (decimal)ImageInfo.Height / height)
            {
                height = (int)((decimal)width * HeigthWidthRatio);
            }
            else
            {
                width = (int)((decimal)height / HeigthWidthRatio);
            }

            return this.GenerateResizedImage(width, height, ImageInfo);
        }

        /// &lt;summary&gt;
        /// To geneterate thumbnail image
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;width&quot;&gt;image width&lt;/param&gt;
        /// &lt;param name=&quot;height&quot;&gt; image height&lt;/param&gt;
        /// &lt;param name=&quot;Imageinfo&quot;&gt; image informations&lt;/param&gt;
        /// &lt;returns&gt;thumbnail image&lt;/returns&gt;
        private Image GenerateResizedImage(int width, int height, Image Imageinfo)
        {
            if (width &lt;= 0 | height &lt;= 0)
            {
                throw new Exception(&quot;Either width or heigth has invalid value&quot;);
            }

            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();
            }
        }
    }
}

</pre></p>
<p>Next Step is create a custom <strong>ActionResult </strong>for handling image content type. I have created the folder named ActionResult and i created the ActionResult name <strong>ImageActionResult</strong>  .</p>
<p>I am going to make the response content type to the browser as <strong>image/jpeg</strong> content type. This is achieved by overriding the <strong>ExecuteResult </strong>method of the ActionResult.</p>
<p><pre class="brush: csharp;">

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
{
    /// &lt;summary&gt;
    /// To save and retrieve image in different sizes.
    /// &lt;/summary&gt;
    public class ImageActionResult : ActionResult
    {

        private Image _SourceImage;

        /// &lt;summary&gt;
        /// Gets or sets the image.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;SourceImage&quot;&gt;resized image details&lt;/param&gt;
        public ImageActionResult(Image SourceImage)
        {
            this._SourceImage = SourceImage;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            this.GenerateImage(context);
        }

        /// &lt;summary&gt;
        /// save different size of image
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;context&quot;&gt;&lt;/param&gt;
        private void GenerateImage(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = &quot;image/jpeg&quot;;
            this._SourceImage.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg);
            this._SourceImage.Dispose();
        }
    }
}


</pre></p>
<p>Next step to MapRoute in the <strong>Global.asax.cs</strong> file.  I made the default  controller as <strong>Image </strong>and default action as <strong>VaryImageSize</strong>. 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</p>
<p><em>http://localhost:1230/Image/VaryImageSize/200/200</em></p>
<p>here the values of 200 refers to width and height of the image to be resized</p>
<p><pre class="brush: csharp;">

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(&quot;{resource}.axd/{*pathInfo}&quot;);
    
            routes.MapRoute(
                &quot;Default&quot;,                                              
                &quot;{controller}/{action}/{width}/{height}&quot;,                           
                new { controller = &quot;Image&quot;, action = &quot;VaryImageSize&quot;, width = &quot;&quot;, height = &quot;&quot;}); 


        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

</pre></p>
<p>Last Step to create Controller name <strong>ImageController </strong>and Action named <strong>VaryImageSize </strong>with the return type as <strong>ImageAction </strong>Result which make the response Content type as Image.</p>
<p><strong>VaryImageASize </strong>Action accepts two parameter named width and height.</p>
<p>Here i am using static image named &#8220;<strong>sample.jpg</strong>&#8221; fro resizing which is located in the images folder. Any one can implement there own functionality to load the image.</p>
<p>The below image is the sample.jpg image i have used in this project</p>
<p><a href="http://jaganeee.files.wordpress.com/2010/02/sample.jpg"><img class="alignnone size-full wp-image-52" title="sample" src="http://jaganeee.files.wordpress.com/2010/02/sample.jpg?w=455" alt=""   /></a></p>
<p>I haven&#8217;t done any input parameter validation for width and height.<br />
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</p>
<p><em>http://localhost:1230/Image/VaryImageSize</em></p>
<p>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</p>
<p><em>http://localhost:1230/Image/VaryImageSize/80</em></p>
<p>Here the 80 refers to the 80% of the original size to be resized</p>
<p>If there is any error throws then &#8220;<strong>noimage.jpg</strong>&#8221;  is shown as the output image</p>
<p>This is the noimage.jpg file</p>
<p><a href="http://jaganeee.files.wordpress.com/2010/02/noimage.jpg"><img class="alignnone size-full wp-image-51" title="noimage" src="http://jaganeee.files.wordpress.com/2010/02/noimage.jpg?w=455" alt=""   /></a></p>
<p>This is the ImageController Class File.</p>
<p><pre class="brush: csharp;">

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 + &quot;images/sample.jpg&quot;;

            ImageEditing imgedit = new ImageEditing(originalFilePath);

            Image resultimage;

            try
            {

                if (width == string.Empty &amp;&amp; height == string.Empty)
                {
                    resultimage = imgedit.Resize(100);
                }

                else
                {

                    Int16.TryParse(width, out WidthToResize);
                    Int16.TryParse(height, out HeightToResize);

                    if (WidthToResize &lt;= 0)
                    {
                        throw new Exception();
                    }

                    if (HeightToResize &lt;= 0)
                    {
                        resultimage = imgedit.Resize(WidthToResize);
                    }
                    else
                    {
                        resultimage = imgedit.Resize(WidthToResize, HeightToResize);
                    }
                }
                
            }

            catch
            {
                resultimage = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + &quot;images/noimage.jpg&quot;);
            }

            return new ImageActionResult(resultimage);
        }


    }
}


</pre></p>
<p>Some of the Sample Url that shows the resized image content are</p>
<p><em>http://localhost:1230/Image/VaryImageSize/200/200</em> &#8211; Shows the image resized to 200 x 200</p>
<p><em>http://localhost:1230/Image/VaryImageSize/80</em> &#8211; Shows the resized image reduced by 80% of original image</p>
<p><em>http://localhost:1230/Image/VaryImageSize</em> &#8211; Shows the original image</p>
<p>That&#8217;s the end of the article. Hope u can find the way to resize the image in ASP.NET MVC.</p>
<p>As this is my first article in the web your feedback and suggestion are welcome.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jaganeee.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jaganeee.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jaganeee.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jaganeee.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jaganeee.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jaganeee.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jaganeee.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jaganeee.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jaganeee.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jaganeee.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jaganeee.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jaganeee.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jaganeee.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jaganeee.wordpress.com/18/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jaganeee.wordpress.com&amp;blog=3894309&amp;post=18&amp;subd=jaganeee&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jaganeee.wordpress.com/2010/02/10/image-resize-using-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2f9d02a6dda7c1a8dd1d3cef8f45fc7f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jaganeee</media:title>
		</media:content>

		<media:content url="http://jaganeee.files.wordpress.com/2010/02/sample.jpg" medium="image">
			<media:title type="html">sample</media:title>
		</media:content>

		<media:content url="http://jaganeee.files.wordpress.com/2010/02/noimage.jpg" medium="image">
			<media:title type="html">noimage</media:title>
		</media:content>
	</item>
	</channel>
</rss>
