Home Blog Work

Re-size Image On Fly In ASP.NET

Published on January 23, 2013

In one of my previous post i wrote how to re-size images on fly using php. Today i am going to show you how to do the same thing in ASP.NET. In Uploading Image with ASP.NET-WebImage helper post i mentioned WebImage is a special helper for web image manuplation. Today we will use that WebImage helper to resize images on fly in ASP.NET. Re-size Image On Fly In ASP.NET

The task is simple, first we ask user to upload image with expected image height and width. We will pass those parameter to WebImage.Resize function. WebImage will generate new image with expected height and width. We will display it to user. Let’s start. If you already following previous articals Uploading Image With ASP.NET(Razor-WebImage) you don’t need to follow steps 1 to 6. I am assuming you have installed Visual studio Express for web 2012. Now follow the following steps. 1)Open your VS Express For Web(go all programs search for vs express for web). 2)Create a New Web Site Under File Menu. Re-size Image On Fly In ASP.NET 3)Add New Content Page(Razor v2) to website and name it as imageresize.cshtml. Re-size Image On Fly In ASP.NET 4)Right Click on your website and select Manage Nuget Packages. Re-size Image On Fly In ASP.NET 5)Search with keyword helper in top right search box, from the result install ASP.NET Web Helper Library Re-size Image On Fly In ASP.NET 6)Next step it will ask for Licence Acceptance, You have to click on I agree button. Re-size Image On Fly In ASP.NET 7)Now Copy Pat the following code in imageresize.cshtml

Page.Title = "Image Resizing on fly";
Layout = "~/_SiteLayout.cshtml";

WebImage img = null;
var newImgPath = "";
var oldImg = "";
var oldImgpath = "";

var w = Convert.ToInt32(Request.Form["w"]);
var h = Convert.ToInt32(Request.Form["h"]);
img = WebImage.GetImageFromRequest();
oldImg = Path.GetFileName(img.FileName);
oldImgpath = @"Uploads\" + oldImg;
img.Save(@"~\" + oldImgpath);

newImgPath = @"Uploads\smallImg\" + "s_"+oldImg;
img.Resize(width: w, height: h, preserveAspectRatio: true,
preventEnlarge: true);
img.Save(@"~\" + newImgPath); }

<!DOCTYPE html>
<title>Image Resizing on fly</title>
<h1>Image Resizing on fly</h1>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="img" />
<input type="number" name="w" />
<input type="number" name="h" />
<input type="submit" value="Submit" />
@if (newImgPath != "")
<div class="result">
<div style="float:left;margin-right:11px">
<label>New Image</label>
<img src="@newImgPath" />
<label>Old Image</label>
<img src="@oldImgpath" />

8)Expected Out put as below. Re-size Image On Fly In ASP.NET Re-size Image On Fly In ASP.NET