ASP. NET method for uploading pictures and generating thumbnails

  • 2021-07-10 19:27:01
  • OfStack

This article describes the example of ASP. NET to upload pictures and generate thumbnail method. Share it for your reference, as follows:


protected void bt_upload_Click(object sender, EventArgs e)
{
  // Check whether the uploaded file format is valid  
  if (this.UploadFile.PostedFile.ContentType.ToLower().IndexOf("image") < 0)
  {
   Response.Write(" The uploaded picture format is invalid! ");
   return;
  }
  // Generate original image  
  Byte[] oFileByte = new byte[this.UploadFile.PostedFile.ContentLength];
  System.IO.Stream oStream = this.UploadFile.PostedFile.InputStream;
  System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
  int oWidth = oImage.Width; // Width of original drawing  
  int oHeight = oImage.Height; // Height of original image  
  int tWidth = 100; // Set the initial width of thumbnail  
  int tHeight = 100; // Set the initial height of thumbnail  
  // Calculate the width and height of thumbnails to scale  
  if (oWidth >= oHeight)
  {
   tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
  }
  else
  {
   tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
  }
  // Generate thumbnail original image  
  Bitmap tImage = new Bitmap(tWidth, tHeight);
  Graphics g = Graphics.FromImage(tImage);
  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; // Set up high-quality interpolation method  
  g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;// Set high quality , Smooth degree at low speed  
  g.Clear(Color.Transparent); // Empty the canvas and fill it with a transparent background color  
  g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
  string oFullName = Server.MapPath(".") + "/image/" + "o" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".jpg"; // Save the physical path of the original image  
  string tFullName = Server.MapPath(".") + "/image/" + "t" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".jpg"; // Save the physical path of the thumbnail  
  try
  {
   // With JPG Save pictures in format  
   oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
   tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
  }
  catch (Exception ex)
  {
   throw ex;
  }
  finally
  {
   // Release resources  
   oImage.Dispose();
   g.Dispose();
   tImage.Dispose();
  }
 }
}

Here is another improvement method:


#region  Upload pictures   And generate thumbnails 
/// <summary>
///  Upload pictures to generate thumbnails 
/// </summary>
/// <param name="originalImagePath"> Image source path </param>
/// <param name="thumbnailPath"> Thumbnail path ( Physical path )</param>
/// <param name="width"> Thumbnail width </param>
/// <param name="height"> Thumbnail height </param>
/// <param name="mode"> How to generate thumbnails </param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) {
  // File that gets the source picture from the path 
  System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
  int towidth = width;
  int toheight = height;
  int x = 0;
   int y = 0;
  // Gets the width of the picture 
   int ow = image.Width;
  // Get the height of the picture 
   int oh = image.Height;
  // How to generate thumbnails 
   switch (mode) { 
    case "HW":
    break;
    case "W":// Specify Width   Highly proportional 
    toheight = originalImage.Height * width / originalImage.Width;
    break;
    case "H":// Specify the height of the picture   Width proportional 
    towidth = originalImage.Width * height / originalImage.Height;
    break;
    case "Cut":// If you are in trimming mode   It is not deformed  
    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
    {
     oh = originalImage.Height;
     // Width of thumbnail picture 
     ow = originalImage.Height * towidth / toheight;
     y = 0;
     x = (originalImage.Width - ow) / 2;
    }
    else {
     ow = originalImage.Width;
     // Height of thumbnail picture 
     oh = originalImage.Width * toheight / towidth;
     x = 0;
     y(originalImage.Height - oh) / 2;
    }
    break;
    default: break;
   }
  // New 1 A bmp Picture 
   Bitmap bitmap = new Bitmap(towidth, toheight);
  // New 1 Canvas   With BitMap  Width   Height as the size of the canvas 
   Graphics g = Graphics.FromImage(bitmap);
  // Set up high-quality interpolation method 
   g.InterpolationMode = InterpolationMode.High;
  // With high quality   Low speed   Render 
   g.SmoothingMode = SmoothingMode.HighQuality;
  // Empty a canvas   Fill with white background color  
   g.Clear(Color.Transparent);
   // Draws the specified part of the original picture at the specified position and at the specified size 
   g.DrawImage(originalImage,new Rectangle(towidth,toheight),new Rectangle(x,y,ow,oh),GraphicsUnit.Pixel);
   try
   {
    // With jpg Format to save thumbnails 
    bitmap.Save(thumbnailPath,System.Drawing.Imaging.ImageFormat.Jpeg);
   }
   catch (Exception ex)
   {
    throw ex;
   }
   finally {
    // Release resources 
    originalImage.Dispose();
    bitmap.Dispose();
    g.Dispose();
   }
}
#endregion

I hope this article is helpful to everyone's asp. net programming.


Related articles: