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 (43)
  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

First one is for status messages shown at the top of the page. Next comes the HtmlForm control which contains 3 HtmlInputFile controls.

Note: The 'enctype' attribute of 'form' has been set to 'multipart/form-data' to allow us to upload files.

Let's see what our code-behind class looks like.

iv. upload.aspx.cs
This class is the code-behind for upload.aspx page you saw above. It contains the code which handles uploading of upto 3 image files simultaneously. Different rules are applied to those 3 image files. The first one's size should be between 5 KB and 20 KB, second one's width and height should be less than 300 pixels, while there is no restriction on the size and dimensions of the third one. These restrictions have only been placed to teach you how to limit image uploading to a certain size or dimension.

Next it creates an extra thumbnail ( 150x150 pixel ) for every image uploaded.

Now create a new file as upload.aspx.cs and copy/paste following code in it:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

namespace Stardeveloper.UploadImage
{
  public class UploadForm : System.Web.UI.Page
  {
    public const int MaxWidth = 300;
    public const int MaxHeight = 300;

    public const int MinSize = 5 * 1024;
    public const int MaxSize = 20 * 1024;

    public const int ThumbnailWidth = 150;
    public const int ThumbnailHeight = 150;

    protected HtmlGenericControl message;

    protected HtmlInputFile file;
    protected HtmlInputFile file1;
    protected HtmlInputFile file2;

    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.");
      }
    }

    private void AppendMessage(string msg)
    {
      message.Controls.Add(new LiteralControl(msg));
    }

    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>");
        }
      }
    }

    private bool IsImage(HttpPostedFile file)
    {
      if(file != null && Regex.IsMatch(file.ContentType, "image/\\S+") &&
        file.ContentLength > 0)
      {
        DisplayImageInfo(file);
        return true;
      }

      return false;
    }

    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));
        }
      }
    }

    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));
          }
        }
      }
    }

    protected void UploadImageWithNoRestrictions(HttpPostedFile file)
    {
      if(IsImage(file))
      {
        UploadImage(file);
      }
    }

    protected void UploadImage(HttpPostedFile file)
    {
      string fileName =
        file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);
      string filePath = MapPath("uploaded_images/" + fileName);

      file.SaveAs(filePath);
      AppendMessage("<span style=\"color:green;\">File Uploaded...</span><br>");

      using(System.Drawing.Image image =
        System.Drawing.Image.FromStream(file.InputStream))
      using(Bitmap bitmap = new Bitmap(image, ThumbnailWidth, ThumbnailHeight))
      {
        bitmap.Save(MapPath("uploaded_images/t__" + fileName), image.RawFormat);
        AppendMessage("<span style=\"color:green;\">Thumbnail" +
          " created...</span><br><br>");
      }
    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
    
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
      this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
  }
}

Previous ( 4 Gone )( 5 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.