C# - 建立縮圖

by | |

public void MakeThumbnail( string sourceImagePath, string thumbnailPath, int width, int height, string mode)
  {
   System.Drawing.Image originalImage = System.Drawing.Image.FromFile (sourceImagePath);
   int x = 0;
   int y = 0;
   int ow = originalImage.Width;
   int oh = originalImage.Height;
   switch (mode)
   {
     // 指定高寬縮放(可能變形)
    case "HW":
     break;
     // 指定寬度,高度按比例
    case "W":
     height = originalImage.Height*width/originalImage.Width;
     break;
     // 指定高度,寬度按比例
    case "H":
     width = originalImage.Width*height/originalImage.Height;
     break;
     //指定高寬裁減(不變形)
    case "CUT":
     if ( ( ( double ) originalImage.Width )/originalImage.Height > ( ( double ) width)/height)
     {
      oh = originalImage.Height;
      ow = originalImage.Height*width/height;
      y = 0;
      x = (originalImage.Width - ow)/2;
     }
     else
     {
      ow = originalImage.Width;
      oh = originalImage.Width*height/width;
      x = 0;
      y = (originalImage.Height - oh)/2;
     }
     break;
    default:
     break;
   }
   System.Drawing.Image bitmap = new Bitmap(width, height);
   Graphics g = Graphics.FromImage (bitmap);
   g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //InterpolationMode.High;
   //    g.SmoothingMode = SmoothingMode.HighQuality;
   g.Clear (Color.Transparent );
   g.DrawImage (originalImage, new Rectangle( 0, 0, width, height), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel );
   // bitmap.Save (thumbnailPath, ImageFormat.Png );
   bitmap.Save(thumbnailPath,System.Drawing.Imaging.ImageFormat.Png) ;
  }

0 意見:

張貼留言

Related Posts Plugin for WordPress, Blogger...