Stephen Daly - ASP.net/C# developer & technology enthusiast

Image upload with a specific width & height ratio

While working on the message board for my brothers band site (Black Soul Strangers) today, i needed to let users upload a profile picture but i didnt want it to exceed the 60px*60px and i also wanted to keep the Width*Height ratio. Here is the code i developed to do this: 

// This method uploads the file
public void uploadFile(object sender, EventArgs e)

{

    string SaveLocation = "";

    string filename = "";

   
int MAXFILESIZE = 10000;
    int MAXWIDTH = 60;

    int MAXHEIGHT = 60;

    float width, height;

 // Checks to see if there is a file to be uploaded

   if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
    {

       if (FileUpload1.PostedFile.ContentLength <= MAXFILESIZE)

        {

            SaveLocation = Server.MapPath(".") + "\\images\\profilepics\\";

            EnsureDirectory(new System.IO.DirectoryInfo(SaveLocation));

            filename = FileUpload1.PostedFile.ContentType;

            string[] filetype = filename.Split('/');
            filename = User.Identity.Name.ToUpper() + "." + filetype[1];
            SaveLocation = SaveLocation + "\\" + filename;
            string SaveLocationSQL = "images/profilepics/" + filename;
            FileUpload1.PostedFile.SaveAs(SaveLocation);

            Bitmap i = new Bitmap(SaveLocation);                  

            height = MAXHEIGHT;
            width = (height / i.Height) * i.Width;
 

            if (width > MAXWIDTH)
             {

               height = (
MAXHEIGHT / width) * height;

               width = MAXWIDTH;
             }

            i.Dispose();
            FileUpload1.Dispose();

            BSSUser u = new BSSUser();

            u.UserID = userid;

            u.PicUrl = SaveLocationSQL;

            u.PicHeight = Convert.ToInt32(height);

            u.PicWidth = Convert.ToInt32(width);

            u.changeProfilePic(u);

            Response.Redirect("MyAccount.aspx");

        }

     else
        {

            lblFileUpload.Text = "TOO LARGE - MAX SIZE IS 10KB";

            lblFileUpload.ForeColor = System.Drawing.Color.Red;

         }

   }

  // Returns null if there is no file to be uploaded
  else

    {

       Response.Redirect("Error.aspx");

    }

}


// checks if the directory exists. If not, it will create it

public void EnsureDirectory(System.IO.DirectoryInfo DirInfo)

{

   if (DirInfo.Parent != null)

       EnsureDirectory(DirInfo.Parent);

   if (!DirInfo.Exists)

     {

       DirInfo.Create();

     }

}


Posted by: Stephen
Posted on: 08/03/2009 at 9:09 AM
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading