123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- using System.Collections.Generic;
- using System.Drawing;
- using System.IO;
- namespace GxPress.Common.Tools
- {
- /// <summary>
- /// 压缩图片
- /// </summary>
- public class CompressImage
- {
- /// <summary>
- /// 开始压缩图片
- /// </summary>
- /// <param name="fileName">图片路径</param>
- /// <param name="width">图片格式大小 默认 50*50</param>
- public static void Execute(string fileName = "", int width = 50)
- {
- //获取图片的返回类型
- var contentTypDict = new Dictionary<string, string> {
- {"jpg","image/jpeg"},
- {"JPG","image/jpeg"},
- {"jpeg","image/jpeg"},
- {"JPEG","image/jpeg"},
- {"jpe","image/jpeg"},
- {"png","image/png"},
- {"gif","image/gif"},
- {"ico","image/x-ico"},
- {"tif","image/tiff"},
- {"tiff","image/tiff"},
- {"fax","image/fax"},
- {"wbmp","image//vnd.wap.wbmp"},
- {"rp","image/vnd.rn-realpix"}
- };
- var imgTypeSplit = fileName.Split('.');
- var contentTypeStr = "image/jpeg";
- var imgType = imgTypeSplit[imgTypeSplit.Length - 1];
- //未知的图片类型
- if (!contentTypDict.ContainsKey(imgType.ToLower()))
- return;
- else
- contentTypeStr = contentTypDict[imgType];
- //图片不存在
- if (!new FileInfo(fileName).Exists)
- return;
- if (fileName.Contains("50_50") || fileName.Contains("100_100"))
- return;
- //缩小图片
- var imageName = $"_{width}_{width}.{imgType}";
- var searchFileName = fileName.Replace($".{imgType}", imageName);
- if (File.Exists(searchFileName))
- return;
- using (var imgBmp = new Bitmap(fileName))
- {
- //找到新尺寸
- var oWidth = imgBmp.Width;
- var oHeight = imgBmp.Height;
- var height = oHeight;
- if (width > oWidth)
- width = oWidth;
- else
- height = width * oHeight / oWidth;
- var newImg = new Bitmap(imgBmp, width, height);
- newImg.SetResolution(72, 72);
- var ms = new MemoryStream();
- newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
- var bytes = ms.GetBuffer();
- //保存图片
- Image image = Image.FromStream(ms);
- fileName = fileName.Replace($".{imgType}", imageName);
- image.Save(fileName);
- ms.Close();
- imgBmp.Dispose();
- }
- }
- }
- }
|