CompressImage.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Collections.Generic;
  2. using System.Drawing;
  3. using System.IO;
  4. namespace GxPress.Common.Tools
  5. {
  6. /// <summary>
  7. /// 压缩图片
  8. /// </summary>
  9. public class CompressImage
  10. {
  11. /// <summary>
  12. /// 开始压缩图片
  13. /// </summary>
  14. /// <param name="fileName">图片路径</param>
  15. /// <param name="width">图片格式大小 默认 50*50</param>
  16. public static void Execute(string fileName = "", int width = 50)
  17. {
  18. //获取图片的返回类型
  19. var contentTypDict = new Dictionary<string, string> {
  20. {"jpg","image/jpeg"},
  21. {"JPG","image/jpeg"},
  22. {"jpeg","image/jpeg"},
  23. {"JPEG","image/jpeg"},
  24. {"jpe","image/jpeg"},
  25. {"png","image/png"},
  26. {"gif","image/gif"},
  27. {"ico","image/x-ico"},
  28. {"tif","image/tiff"},
  29. {"tiff","image/tiff"},
  30. {"fax","image/fax"},
  31. {"wbmp","image//vnd.wap.wbmp"},
  32. {"rp","image/vnd.rn-realpix"}
  33. };
  34. var imgTypeSplit = fileName.Split('.');
  35. var contentTypeStr = "image/jpeg";
  36. var imgType = imgTypeSplit[imgTypeSplit.Length - 1];
  37. //未知的图片类型
  38. if (!contentTypDict.ContainsKey(imgType.ToLower()))
  39. return;
  40. else
  41. contentTypeStr = contentTypDict[imgType];
  42. //图片不存在
  43. if (!new FileInfo(fileName).Exists)
  44. return;
  45. if (fileName.Contains("50_50") || fileName.Contains("100_100"))
  46. return;
  47. //缩小图片
  48. var imageName = $"_{width}_{width}.{imgType}";
  49. var searchFileName = fileName.Replace($".{imgType}", imageName);
  50. if (File.Exists(searchFileName))
  51. return;
  52. using (var imgBmp = new Bitmap(fileName))
  53. {
  54. //找到新尺寸
  55. var oWidth = imgBmp.Width;
  56. var oHeight = imgBmp.Height;
  57. var height = oHeight;
  58. if (width > oWidth)
  59. width = oWidth;
  60. else
  61. height = width * oHeight / oWidth;
  62. var newImg = new Bitmap(imgBmp, width, height);
  63. newImg.SetResolution(72, 72);
  64. var ms = new MemoryStream();
  65. newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
  66. var bytes = ms.GetBuffer();
  67. //保存图片
  68. Image image = Image.FromStream(ms);
  69. fileName = fileName.Replace($".{imgType}", imageName);
  70. image.Save(fileName);
  71. ms.Close();
  72. imgBmp.Dispose();
  73. }
  74. }
  75. }
  76. }