ASP.NET Image uploading with Resizing

前端 未结 14 1844
广开言路
广开言路 2020-11-30 01:27

I have an aspx page which will upload images to server harddisk from client pc

But now i need to change my program in such a way that it would allow me to resize the

14条回答
  •  执笔经年
    2020-11-30 01:41

    This is how I did in my project, based on your condition (height/width) you can change the parameter ie(MaxHeight)

    View Blog Article : How to Resize image while uploading in asp.net using c#

     public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
            {
                var ratio = (double)maxHeight / image.Height;
    
                var newWidth = (int)(image.Width * ratio);
                var newHeight = (int)(image.Height * ratio);
    
                var newImage = new Bitmap(newWidth, newHeight);
                using (var g = Graphics.FromImage(newImage))
                {
                    g.DrawImage(image, 0, 0, newWidth, newHeight);
                }
                return newImage;
            }
    

    On Button click:

    protected void Button1_Click(object sender, EventArgs e)
    {
      lblmsg.Text="";
      if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
      {
        Guid uid = Guid.NewGuid();
        string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
        string SaveLocation = Server.MapPath("LogoImagesFolder") + "\\" + uid+fn;
        try
        {
          string fileExtention = File1.PostedFile.ContentType;
          int fileLenght = File1.PostedFile.ContentLength;
          if (fileExtention == "image/png" || fileExtention == "image/jpeg" || fileExtention == "image/x-png")
          {
            if (fileLenght <= 1048576)
            {
              System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
              System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
              objImage.Save(SaveLocation,ImageFormat.Png);
              lblmsg.Text = "The file has been uploaded.";
              lblmsg.Style.Add("Color", "Green");
             }
             else 
             {
               lblmsg.Text = "Image size cannot be more then 1 MB.";
               lblmsg.Style.Add("Color", "Red");
              }
           }
         else {
                 lblmsg.Text = "Invaild Format!";
                 lblmsg.Style.Add("Color", "Red");
               }
         }
         catch (Exception ex)
           {
              lblmsg.Text= "Error: " + ex.Message;
              lblmsg.Style.Add("Color", "Red");
           }
       }
     }
    

提交回复
热议问题