ThunbnailTool.cs 3.0 KB

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