Login(Email) Password Forget Password? Account Settings
Home ASP.net System Info C# Books Java Script Visual C++(MFC) C/C++ Win API Java Contact Us
Upload Image File by Measuring Size of Image in C# asp.net

1. Create a Project asp.net (C#) with the name of CSharpUpload (By default webform1.aspx will be crerated)
2.Add the following code in the HTML Code (form tag)

<form id="Form1" method="post" runat="server">
Add the enctype="multipart/form-data" name-value attribute to the <form> tag as follows:
    Code will look like :
3.<form id="Form1" method="post" enctype="multipart/form-data" runat="server">
4.After the opening <form> tag, add the following code:.
<INPUT type=file id=File1 name=File1 runat="server" />
<input type="submit" id="Submit1" value="Upload" runat="server" />
 
Web.config file changes
In the Solution explorer you will see a web.config file. Add the following the <appSettings> Tag.
<appSettings>
  <add key="ImageHeight" value="85"/>
  <add key="ImageWidth" value="85"/>
</appSettings>	

Write the following code in the Webform1.aspx.cs Load Event (read web.config)
In Visual Studio 2008 Please use the following code.
if (Page.IsPostBack)
{
  height = Convert.ToInt32(
       ConfigurationManager.AppSettings.Get("ImageHeight")); 
  width = Convert.ToInt32(
       ConfigurationManager.AppSettings.Get("ImageWidth"));
}
Declare two variables in class section of the form:
like 
int height,width;

In Visual Studio 2003 Please use the following code.

if (Page.IsPostBack)
{
  height = Convert.ToInt32(ConfigurationSettings.AppSettings["ImageHeight"]);
  width = Convert.ToInt32(ConfigurationSettings.AppSettings["ImageWidth"]);
}

Place a label into the webform1.aspx and name it lblMessage.
Write the following code in the Click Event of the Submit Button (Please make a folder in your project directory with the name of sharefolder)

if( ( File1.PostedFile != null ) && ( File1.PostedFile.ContentLength > 0 ) )
{
string extension = Path.GetExtension(File1.PostedFile.FileName);
switch (extension.ToLower())
{
// Only allow uploads that look like images.
case ".jpg" :
case ".jpeg" :
case ".gif" :
case ".bmp" :
try
  {
  if (ValidateFileDimensions())
  {
    string fileName = Path.GetFileName(File1.PostedFile.FileName);
    string saveAsName = Path.Combine(Server.MapPath("~/ShareFolder/"), fileName);
    File1.PostedFile.SaveAs(saveAsName);
 }
  else
  {
   this.lblMessage.Text="Image Size is greater than required Size";
  }
  }
catch(Exception ex)
{
this.lblMessage.Text="Uploading    error: "+ex.ToString();
  }
break;
default:
this.lblMessage.Text="Image format is not supported";
break;
  }
}
else
{
this.lblMessage.Text="Please Browse some image to upload";
 }
 }
public bool ValidateFileDimensions()
{
using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(File1.PostedFile.InputStream))
  {
   return (myImage.Height <= height && myImage.Width <= width);
  }
}

 .Download Code