Yasserzaid’s Weblog

February 9, 2009

Validate Size of Uploaded Images

Filed under: ASP.Net — yasserzaid @ 8:19 pm

Hi

try this Example to Validate size of uploaded image

step1 : create web page and add Fileupload and CustomValidator and button control

Step2 : in web.config file add this

<appSettings>
  <add key=”RequiredHeight” value=”184″/>
  <add key=”RequiredWidth” value=”370″/>
</appSettings>

step3 : to get the hight and width of image  so in Page_Load add this code

if (Page.IsPostBack)
{
  height = Convert.ToInt32(
       ConfigurationManager.AppSettings.Get("RequiredHeight"));
  width = Convert.ToInt32(
       ConfigurationManager.AppSettings.Get("RequiredWidth"));
}

step4: When the user has selected a file and clicked the Upload button, the following code

Page.Validate();
if (Page.IsValid)
{
  if (FileUpload1.HasFile)
  {
    string extension = Path.GetExtension(FileUpload1.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(
                FileUpload1.PostedFile.FileName);
            string saveAsName = Path.Combine(
                Server.MapPath("~/Uploads/"), fileName);
            FileUpload1.PostedFile.SaveAs(saveAsName);
            lblSucces.Visible = true;
          }
          else
          {
            valInvalidDimensions.IsValid = false;
            valInvalidDimensions.ErrorMessage =
              String.Format(valInvalidDimensions.ErrorMessage,
              height, width);
          }
        }
        catch
        {
          // Unable to read the file dimensions.
          // The uploaded file is probably not an image.
          valInvalidFile.IsValid = false;
        }
        break;

      default: // The uploaded file has an incorrect extension
        valInvalidFile.IsValid = false;
        break;
    }
  }
}

step5 : configure CustomValidator control

<asp:CustomValidator
  ID=”valInvalidDimensions”
  runat=”server”
  ErrorMessage=”The image you uploaded has incorrect dimensions.
    Please select a file with a height of {0}px and a width of {1}px.”
  Display=”Dynamic”
  EnableViewState=”false”>
</asp:CustomValidator>

The most important part of the sample page is the ValidateFileDimensions method which is remarkably simple:

public bool ValidateFileDimensions()
{
  using (System.Drawing.Image myImage =
    System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream))
  {
    return (myImage.Height == height && myImage.Width == width);
  }
}
Hope this helps
Good Luck

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.