C# - 建立縮圖

C# - 建立縮圖

  1. public void MakeThumbnail( string sourceImagePath, string thumbnailPath, int width, int height, string mode)
  2. {
  3. Image originalImage = Image.FromFile (sourceImagePath);
  4. int x = 0;
  5. int y = 0;
  6. int ow = originalImage.Width;
  7. int oh = originalImage.Height;
  8. switch (mode)
  9. {
  10. // 指定高寬縮放(可能變形)
  11. case "HW":
  12. break;
  13. // 指定寬度,高度按比例
  14. case "W":
  15. height = originalImage.Height*width/originalImage.Width;
  16. break;
  17. // 指定高度,寬度按比例
  18. case "H":
  19. width = originalImage.Width*height/originalImage.Height;
  20. break;
  21. //指定高寬裁減(不變形)
  22. case "CUT":
  23. if ( ( ( double ) originalImage.Width )/originalImage.Height > ( ( double ) width)/height)
  24. {
  25. oh = originalImage.Height;
  26. ow = originalImage.Height*width/height;
  27. y = 0;
  28. x = (originalImage.Width - ow)/2;
  29. }
  30. else
  31. {
  32. ow = originalImage.Width;
  33. oh = originalImage.Width*height/width;
  34. x = 0;
  35. y = (originalImage.Height - oh)/2;
  36. }
  37. break;
  38. default:
  39. break;
  40. }
  41. Image bitmap = new Bitmap(width, height);
  42. Graphics g = Graphics.FromImage (bitmap);
  43. g.InterpolationMode = InterpolationMode.High;
  44. g.SmoothingMode = SmoothingMode.HighQuality;
  45. g.Clear (Color.Transparent );
  46. g.DrawImage (originalImage, new Rectangle( 0, 0, width, height), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel );
  47. bitmap.Save (thumbnailPath, ImageFormat.Png );
  48. }