Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · ASP.NET Newsletter Application · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Newsletter
Enter your email address to receive full length articles at Stardeveloper:


Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (11)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)

Main Category  Other
  Website Maintenance (3)
Log In
UserName Or Email:

Password:

Auto-Login:

Hosted by Securewebs.com
 
Home : .NET : ASP.NET : Uploading, Determining Size, Width and Height and Resizing Image Files with ASP.NET
 
Read full length articles at Stardeveloper using Twitter Follow on Twitter Facebook Facebook fan page Email Get Articles via Email RSS Get Articles via RSS Feed

Explanation
In the Page_Load() method, we check the IsPostBack property to see if the page has been posted back ( user has clicked the 'submit' button ), if it has then we delegate the work of uploading respective files to respective methods ( with or without restrictions ).

private void Page_Load(object sender, System.EventArgs e)
{
  if(IsPostBack)
  {
    message.Attributes.Add("align", "left");

    UploadImageWithSizeRestrictions(file.PostedFile);
    UploadImageWithDimensionRestrictions(file1.PostedFile);
    UploadImageWithNoRestrictions(file2.PostedFile);
  }
  else
  {
    message.Attributes.Add("align", "center");
    AppendMessage("Select file to upload.");
  }
}

We have also added a method to display useful information to the user about the size, type, width and height of the image. This method is here only for debugging purposes, you should remove it ( and all calls to it ) in the production system as it does nothing but to degrade performance.

private void DisplayImageInfo(HttpPostedFile image)
{
    AppendMessage(String.Format("FileName: {0}<br>", image.FileName));
    AppendMessage(String.Format("FileSize: {0} KB<br>",
      image.ContentLength / 1024));

    using(Bitmap bitmap = new Bitmap(image.InputStream, false))
    {
    AppendMessage(String.Format("Width: {0}<br>", bitmap.Width));
    AppendMessage(String.Format("Height: {0}<br>", bitmap.Height));

    if(bitmap.RawFormat.Equals(ImageFormat.Bmp))
    {
      AppendMessage("ImageFormat: Bitmap Image (BMP)<br>");
    }
    if(bitmap.RawFormat.Equals(ImageFormat.Gif))
    {
      AppendMessage("ImageFormat: Graphics Interchange Format (GIF)<br>");
    }
    if(bitmap.RawFormat.Equals(ImageFormat.Jpeg))
    {
      AppendMessage("ImageFormat: Joint Photographic Experts Group (JPEG)<br>");
    }
    if(bitmap.RawFormat.Equals(ImageFormat.Png))
    {
      AppendMessage("ImageFormat: W3C Portable Network Graphics (PNG)<br>");
    }
  }
}

Then we have another useful method which other methods will call to make sure that the file they are going to process is in fact an image file.

This method uses regular expressions to make sure that the content-type of the uploaded file contains "image/*". It it does then it is an image, otherwise not.

Note: Remove the call to DisplayImageInfo() in production systems.
private bool IsImage(HttpPostedFile file)
{
  if(file != null && Regex.IsMatch(file.ContentType, "image/\\S+") &&
    file.ContentLength > 0)
  {
    DisplayImageInfo(file);
    return true;
  }

  return false;
}

Let us see the code for the first method responsible for uploading image file only if the size of that image is between 5 KB and 20 KB.

Now this is important, lot of users have been asking me how to get to know the size of an uploaded image without actually saving that image on the server. This method illustrates how to do that.

After using IsImage() to check if this is an image file, all it has to do to is to use HttpPosteFiled.ContentLength property to get the size of uploaded file in bytes. It then checks this size against the two minimum ( 5 KB ) and maximum ( 20 KB ) values. If the size is in between those values, it allows uploading of the file by calling our UploadImage() method.

protected void UploadImageWithSizeRestrictions(HttpPostedFile file)
{
  if(IsImage(file))
  {
    int contentLength = file.ContentLength;
    if(contentLength > MinSize && contentLength < MaxSize)
    {
      UploadImage(file);
    }
    else
    {
      AppendMessage(String.Format("<span style=\"color:red;\">Image size " +
        "exceeding limits: {0} KB</span><br><br>",
        contentLength / 1024));
    }
  }
}

Next method makes sure that images with width and height less than 300 pixels each get uploaded. It does that by creating a Bitmap object and then using it's Width and Height properties to determine it's width and height.

Now this is very interesting. I've seen sites that display a form and then ask the user to upload his/her site's logo and then suggesting that user to make sure that width and height are say for example 100x40 pixels. But if the user uploads an image of wider width and height, the form still uploads the image as it doesn't check the width and height of the uploaded image against the required values. Now after seeing the code to do that in this article, you can be sure that you will not make that mistake.

protected void UploadImageWithDimensionRestrictions(HttpPostedFile file)
{
  if(IsImage(file))
  {
    using(Bitmap bitmap = new Bitmap(file.InputStream, false))
    {
      if(bitmap.Width < MaxWidth && bitmap.Height < MaxHeight)
      {
        UploadImage(file);
      }
      else
      {
        AppendMessage(String.Format("<span style=\"color:red;\">Image " +
          "dimensions exceeding limits: {0} x {1}</span><br><br>",
          bitmap.Width, bitmap.Height));
      }
    }
  }
}

Previous ( 5 Gone )( 4 Remaining ) Next

Comments/Questions ( Threads: 32, Comments: 45 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. Ported to VB.NET 2.0
  2. Uploading files to server hard drive (plain ASP)
  3. Ported to VB.net
  4. compression of image size while uploading?????
  5. ASP
  6. Transparant gif images get ugly after resizing
  7. Uploading vs Saving
  8. Automatic thumbnail generation
  9. change the thumbnail size ( 1 Reply )
  10. Parser Error starting default.aspx
  11. Cannot get script to show uploaded files.. in fact they wont upload?
  12. paging pictures
  13. Convert entire application to VB.Net
  14. Sort gallery images by date instead of name ?
  15. Checking if file already exists ? ( 1 Reply )
  16. Image is used by another process
  17. ASP.Net
  18. Please help.
  19. I just cant register the uploadimghd.dll ( 2 Replies ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  20. I just cant register the uploadimghd.dll
  21. VB Script ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  22. Compression of image while uploading
  23. Error... Please help. I'd really like to get this script working! ( 1 Reply )
  24. keeping aspect ratio of the picture ( 3 Replies )
  25. want to upload file on remote server
  26. PNG and BMP Image Types Not Displaying
  27. error on execute build.bat
  28. database pull on picture view
  29. connect to internet ( 2 Replies ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  30. Convert a phrase to VB ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  31. Mini-tutorial ( 1 Reply ) This thread contains 1 reply by the Author of this Article. This thread contains 1 reply by Faisal Khan.
  32. test

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed.

 
© 1999 - 2010 Stardeveloper.com, All Rights Reserved.