ThunbnailTool.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Drawing2D;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Y.Utils.ImageUtils
  9. {
  10. public class ThunbnailTool
  11. {
  12. /// <summary>
  13. /// 标准缩略图生成
  14. /// </summary>
  15. /// <param name="originalImage">原始图像</param>
  16. /// <param name="width">指定宽度</param>
  17. /// <param name="height">指定高度</param>
  18. /// <param name="mode">缩略图模式</param>
  19. /// <param name="im">差值模式</param>
  20. /// <param name="sm">平滑模式</param>
  21. /// <returns></returns>
  22. public static Bitmap Normal(Bitmap originalImage, int width, int height, string mode,
  23. InterpolationMode im = InterpolationMode.High, SmoothingMode sm = SmoothingMode.HighQuality)
  24. {
  25. int towidth = width;
  26. int toheight = height;
  27. int x = 0;
  28. int y = 0;
  29. int ow = originalImage.Width;
  30. int oh = originalImage.Height;
  31. switch (mode)
  32. {
  33. case "HW"://指定高宽缩放(可能变形)
  34. break;
  35. case "W"://指定宽,高按比例
  36. toheight = originalImage.Height * width / originalImage.Width;
  37. break;
  38. case "H"://指定高,宽按比例
  39. towidth = originalImage.Width * height / originalImage.Height;
  40. break;
  41. case "Cut"://指定高宽裁减(不变形)
  42. if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
  43. {
  44. oh = originalImage.Height;
  45. ow = originalImage.Height * towidth / toheight;
  46. y = 0;
  47. x = (originalImage.Width - ow) / 2;
  48. }
  49. else
  50. {
  51. ow = originalImage.Width;
  52. oh = originalImage.Width * height / towidth;
  53. x = 0;
  54. y = (originalImage.Height - oh) / 2;
  55. }
  56. break;
  57. default:
  58. break;
  59. }
  60. //新建一个bmp图片
  61. Bitmap bitmap = new Bitmap(towidth, toheight);
  62. //新建一个画板
  63. Graphics g = Graphics.FromImage(bitmap);
  64. //设置高质量插值法
  65. g.InterpolationMode = im;
  66. //设置高质量,低速度呈现平滑程度
  67. g.SmoothingMode = sm;
  68. //清空画布并以透明背景色填充
  69. g.Clear(Color.Transparent);
  70. //在指定位置并且按指定大小绘制原图片的指定部分
  71. g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
  72. return bitmap;
  73. }
  74. }
  75. }