ImageHelper.cs 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using System;
  6. using System.Drawing;
  7. namespace Azylee.Core.IOUtils.ImageUtils
  8. {
  9. public class ImageHelper
  10. {
  11. /// <summary>
  12. /// 生成缩略图
  13. /// </summary>
  14. /// <param name="originalImagePath">源图路径(物理路径)</param>
  15. /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
  16. /// <param name="width">缩略图宽度</param>
  17. /// <param name="height">缩略图高度</param>
  18. /// <param name="mode">生成缩略图的方式</param>
  19. public static bool MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
  20. {
  21. Image originalImage = Image.FromFile(originalImagePath);
  22. int towidth = width;
  23. int toheight = height;
  24. int x = 0;
  25. int y = 0;
  26. int ow = originalImage.Width;
  27. int oh = originalImage.Height;
  28. switch (mode)
  29. {
  30. case "HW"://指定高宽缩放(可能变形)
  31. break;
  32. case "W"://指定宽,高按比例
  33. toheight = originalImage.Height * width / originalImage.Width;
  34. break;
  35. case "H"://指定高,宽按比例
  36. towidth = originalImage.Width * height / originalImage.Height;
  37. break;
  38. case "Cut"://指定高宽裁减(不变形)
  39. if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
  40. {
  41. oh = originalImage.Height;
  42. ow = originalImage.Height * towidth / toheight;
  43. y = 0;
  44. x = (originalImage.Width - ow) / 2;
  45. }
  46. else
  47. {
  48. ow = originalImage.Width;
  49. oh = originalImage.Width * height / towidth;
  50. x = 0;
  51. y = (originalImage.Height - oh) / 2;
  52. }
  53. break;
  54. default:
  55. break;
  56. }
  57. //新建一个bmp图片
  58. Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
  59. //新建一个画板
  60. Graphics g = System.Drawing.Graphics.FromImage(bitmap);
  61. //设置高质量插值法
  62. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  63. //设置高质量,低速度呈现平滑程度
  64. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  65. //清空画布并以透明背景色填充
  66. g.Clear(Color.Transparent);
  67. //在指定位置并且按指定大小绘制原图片的指定部分
  68. g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
  69. new Rectangle(x, y, ow, oh),
  70. GraphicsUnit.Pixel);
  71. try
  72. {
  73. //以jpg格式保存缩略图
  74. bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
  75. return true;
  76. }
  77. catch (System.Exception e)
  78. {
  79. return false;
  80. //throw e;
  81. }
  82. finally
  83. {
  84. originalImage.Dispose();
  85. bitmap.Dispose();
  86. g.Dispose();
  87. }
  88. }
  89. }
  90. }