How to resize uploaded image in ASP.NET?


In this article I am going to explain about how to resize image in ASP.NET. In many cases user upload large images in the website using this code we can resize that each image and save in the server folder

Description :


If user upload large size of images in the server it occupy more spaces in the server and difficult to view all images in the website. So we need to resize that image during upload and then save it.

Client side


I placed file upload control to get file from user

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Resize Image</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="600" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" height="40">
<b>Resize image</b>
</td>
</tr>
<tr>
<td height="40">
Select File to be uplaod
</td>
<td height="40">
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2" height="40" align="center">
<asp:Button ID="btnUpload" runat="server" Text="Resize and Upload"
onclick="btnUpload_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Server side


In the server side I get that image input stream and resize it like below code

using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//create instance for image class
System.Drawing.Image myimg = default(System.Drawing.Image);
//get uploaded image input stream
myimg = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
//resize it using thumbnailimage method
myimg = myimg.GetThumbnailImage(50, 100, null, IntPtr.Zero);
MemoryStream str = new MemoryStream();
//Save it in the server images folder
myimg.Save(Server.MapPath("~\\images\\" + FileUpload1.FileName), myimg.RawFormat);
Response.Write("Resized image is successfully uploaded in to server images folder");
}
}
}

Output :


image

Source code:


Client Side: ASP.NET
Code Behind: C#

Conclusion

I hope this code snippet is help you to know about resize image in the ASP.NET.


Attachments

  • Resize_Image_Source (43964-73537-Resize-Image-Source.rar)
  • Comments

    Guest Author: Parul08 Aug 2012

    Its working very nice.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: