C simple method for generating thumbnails

  • 2021-01-03 21:01:46
  • OfStack

This article shows an example of how C# can simply generate thumbnails. Share to everybody for everybody reference. Specific implementation methods are as follows:


/// <summary>
///  Generate thumbnails 
/// </summary>
/// <param name="originalImagePath"> Source map path (physical 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)
{
 Image originalImage = Image.FromFile(originalImagePath);
 int towidth = width;
 int toheight = height;
 int x = 0;
 int y = 0;
 int ow = originalImage.Width;
 int oh = originalImage.Height; 
 switch (mode)
 { 
  case "HW":// Specify height and width scaling (possible distortion)    
   break;
  case "W":// Specify width and height proportionally    
   toheight = originalImage.Height * width/originalImage.Width;
   break;
  case "H":// Specify height and width in proportion 
   towidth = originalImage.Width * height/originalImage.Height;   
   break; 
  case "Cut":// Specified height and width cut (without deformation)    
   if((double)originalImage.Width/(double)originalImage.Height > (double)towidth/(double)toheight)
   {
   oh = originalImage.Height;
   ow = originalImage.Height*towidth/toheight;
   y = 0;
   x = (originalImage.Width - ow)/2;
   }
   else
   {
   ow = originalImage.Width;
   oh = originalImage.Width*height/towidth;
   x = 0;
   y = (originalImage.Height - oh)/2;
   }
   break;   
  default :
   break;
 } 
 // new 1 a bmp The picture 
 Image bitmap = new System.Drawing.Bitmap(towidth,toheight);
 // new 1 A drawing board 
 Graphics g = System.Drawing.Graphics.FromImage(bitmap);
 // Set up a high quality interpolation 
 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
 // Set high quality , Low speed presents smoothness 
 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
 // Empty the canvas and fill it with a transparent background color 
 g.Clear(Color.Transparent); 
 // Draws the specified part of the original image at the specified location and at the specified size 
 g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
  new Rectangle(x, y, ow,oh),
  GraphicsUnit.Pixel);
 try
 {  
  // In order to jpg Format to save thumbnails 
  bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
 }
 catch(System.Exception e)
 {
  throw e;
 }
 finally
 {
  originalImage.Dispose();
  bitmap.Dispose();    
  g.Dispose();
 }
}

Hopefully this article has helped you with your C# programming.


Related articles: