ThunbnailTool.cs 3.2 KB

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