ImageUtilities.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Drawing2D;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace Masuit.Tools.Media
  9. {
  10. /// <summary>
  11. /// 图片处理
  12. /// </summary>
  13. public static class ImageUtilities
  14. {
  15. #region 正方型裁剪并缩放
  16. /// <summary>
  17. /// 正方型裁剪
  18. /// 以图片中心为轴心,截取正方型,然后等比缩放
  19. /// 用于头像处理
  20. /// </summary>
  21. /// <param name="fromFile">原图Stream对象</param>
  22. /// <param name="fileSaveUrl">缩略图存放地址</param>
  23. /// <param name="side">指定的边长(正方型)</param>
  24. /// <param name="quality">质量(范围0-100)</param>
  25. public static void CutForSquare(this Stream fromFile, string fileSaveUrl, int side, int quality)
  26. {
  27. //创建目录
  28. string dir = Path.GetDirectoryName(fileSaveUrl);
  29. Directory.CreateDirectory(dir);
  30. //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
  31. var initImage = Image.FromStream(fromFile, true);
  32. //原图宽高均小于模版,不作处理,直接保存
  33. if ((initImage.Width <= side) && (initImage.Height <= side))
  34. {
  35. initImage.Save(fileSaveUrl);
  36. }
  37. else
  38. {
  39. //原始图片的宽、高
  40. int initWidth = initImage.Width;
  41. int initHeight = initImage.Height;
  42. //非正方型先裁剪为正方型
  43. if (initWidth != initHeight)
  44. {
  45. //截图对象
  46. Image pickedImage;
  47. Graphics pickedG;
  48. //宽大于高的横图
  49. if (initWidth > initHeight)
  50. {
  51. //对象实例化
  52. pickedImage = new Bitmap(initHeight, initHeight);
  53. pickedG = Graphics.FromImage(pickedImage);
  54. //设置质量
  55. pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
  56. pickedG.SmoothingMode = SmoothingMode.HighQuality;
  57. //定位
  58. Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
  59. Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
  60. //画图
  61. pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
  62. //重置宽
  63. initWidth = initHeight;
  64. }
  65. //高大于宽的竖图
  66. else
  67. {
  68. //对象实例化
  69. pickedImage = new Bitmap(initWidth, initWidth);
  70. pickedG = Graphics.FromImage(pickedImage);
  71. //设置质量
  72. pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
  73. pickedG.SmoothingMode = SmoothingMode.HighQuality;
  74. //定位
  75. Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
  76. Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
  77. //画图
  78. pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
  79. //重置高
  80. initHeight = initWidth;
  81. }
  82. //将截图对象赋给原图
  83. initImage = (Image)pickedImage.Clone();
  84. //释放截图资源
  85. initImage.Dispose();
  86. pickedG.Dispose();
  87. pickedImage.Dispose();
  88. }
  89. //缩略图对象
  90. using Image resultImage = new Bitmap(side, side);
  91. using var resultG = Graphics.FromImage(resultImage);
  92. //设置质量
  93. resultG.InterpolationMode = InterpolationMode.HighQualityBicubic;
  94. resultG.SmoothingMode = SmoothingMode.HighQuality;
  95. //用指定背景色清空画布
  96. resultG.Clear(Color.White);
  97. //绘制缩略图
  98. resultG.DrawImage(initImage, new Rectangle(0, 0, side, side), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel);
  99. //关键质量控制
  100. //获取系统编码类型数组,包含了jpeg,bmpp,png,gif,tiff
  101. var icis = ImageCodecInfo.GetImageEncoders();
  102. ImageCodecInfo ici = null;
  103. foreach (var i in icis)
  104. {
  105. if ((i.MimeType == "image/jpeg") || (i.MimeType == "image/bmpp") || (i.MimeType == "image/png") || (i.MimeType == "image/gif"))
  106. ici = i;
  107. }
  108. using var ep = new EncoderParameters(1)
  109. {
  110. Param =
  111. {
  112. [0] = new EncoderParameter(Encoder.Quality, quality)
  113. }
  114. };
  115. //保存缩略图
  116. resultImage.Save(fileSaveUrl, ici, ep);
  117. }
  118. }
  119. #endregion 正方型裁剪并缩放
  120. #region 自定义裁剪并缩放
  121. /// <summary>
  122. /// 指定长宽裁剪
  123. /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
  124. /// </summary>
  125. /// <param name="fromFile">原图Stream对象</param>
  126. /// <param name="fileSaveUrl">保存路径</param>
  127. /// <param name="maxWidth">最大宽(单位:px)</param>
  128. /// <param name="maxHeight">最大高(单位:px)</param>
  129. /// <param name="quality">质量(范围0-100)</param>
  130. public static void CutForCustom(this Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
  131. {
  132. //从文件获取原始图片,并使用流中嵌入的颜色管理信息
  133. using var initImage = Image.FromStream(fromFile, true);
  134. //原图宽高均小于模版,不作处理,直接保存
  135. if ((initImage.Width <= maxWidth) && (initImage.Height <= maxHeight))
  136. {
  137. initImage.Save(fileSaveUrl);
  138. }
  139. else
  140. {
  141. //模版的宽高比例
  142. double templateRate = (double)maxWidth / maxHeight;
  143. //原图片的宽高比例
  144. double initRate = (double)initImage.Width / initImage.Height;
  145. //原图与模版比例相等,直接缩放
  146. if (templateRate == initRate)
  147. {
  148. //按模版大小生成最终图片
  149. Image templateImage = new Bitmap(maxWidth, maxHeight);
  150. Graphics templateG = Graphics.FromImage(templateImage);
  151. templateG.InterpolationMode = InterpolationMode.High;
  152. templateG.SmoothingMode = SmoothingMode.HighQuality;
  153. templateG.Clear(Color.White);
  154. templateG.DrawImage(initImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
  155. templateImage.Save(fileSaveUrl, initImage.RawFormat);
  156. }
  157. //原图与模版比例不等,裁剪后缩放
  158. else
  159. {
  160. //裁剪对象
  161. Image pickedImage;
  162. Graphics pickedG;
  163. //定位
  164. Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位
  165. Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位
  166. //宽为标准进行裁剪
  167. if (templateRate > initRate)
  168. {
  169. //裁剪对象实例化
  170. pickedImage = new Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate));
  171. pickedG = Graphics.FromImage(pickedImage);
  172. //裁剪源定位
  173. fromR.X = 0;
  174. fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
  175. fromR.Width = initImage.Width;
  176. fromR.Height = (int)Math.Floor(initImage.Width / templateRate);
  177. //裁剪目标定位
  178. toR.X = 0;
  179. toR.Y = 0;
  180. toR.Width = initImage.Width;
  181. toR.Height = (int)Math.Floor(initImage.Width / templateRate);
  182. }
  183. //高为标准进行裁剪
  184. else
  185. {
  186. pickedImage = new Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height);
  187. pickedG = Graphics.FromImage(pickedImage);
  188. fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
  189. fromR.Y = 0;
  190. fromR.Width = (int)Math.Floor(initImage.Height * templateRate);
  191. fromR.Height = initImage.Height;
  192. toR.X = 0;
  193. toR.Y = 0;
  194. toR.Width = (int)Math.Floor(initImage.Height * templateRate);
  195. toR.Height = initImage.Height;
  196. }
  197. //设置质量
  198. pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
  199. pickedG.SmoothingMode = SmoothingMode.HighQuality;
  200. //裁剪
  201. pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
  202. //按模版大小生成最终图片
  203. using Image templateImage = new Bitmap(maxWidth, maxHeight);
  204. using Graphics templateG = Graphics.FromImage(templateImage);
  205. templateG.InterpolationMode = InterpolationMode.High;
  206. templateG.SmoothingMode = SmoothingMode.HighQuality;
  207. templateG.Clear(Color.White);
  208. templateG.DrawImage(pickedImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, pickedImage.Width, pickedImage.Height), GraphicsUnit.Pixel);
  209. //关键质量控制
  210. //获取系统编码类型数组,包含了jpeg,bmpp,png,gif,tiff
  211. ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
  212. ImageCodecInfo ici = null;
  213. foreach (var i in icis)
  214. {
  215. if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmpp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
  216. ici = i;
  217. }
  218. EncoderParameters ep = new EncoderParameters(1);
  219. ep.Param[0] = new EncoderParameter(Encoder.Quality, quality);
  220. //保存缩略图
  221. templateImage.Save(fileSaveUrl, ici, ep);
  222. pickedG.Dispose();
  223. pickedImage.Dispose();
  224. }
  225. }
  226. }
  227. #endregion 自定义裁剪并缩放
  228. #region 等比缩放
  229. /// <summary>
  230. /// 图片等比缩放
  231. /// </summary>
  232. /// <param name="fromFile">原图Stream对象</param>
  233. /// <param name="savePath">缩略图存放地址</param>
  234. /// <param name="targetWidth">指定的最大宽度</param>
  235. /// <param name="targetHeight">指定的最大高度</param>
  236. /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
  237. /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
  238. public static void ZoomAuto(this Stream fromFile, string savePath, double targetWidth, double targetHeight, string watermarkText, string watermarkImage)
  239. {
  240. //创建目录
  241. string dir = Path.GetDirectoryName(savePath);
  242. Directory.CreateDirectory(dir);
  243. //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
  244. using Image initImage = Image.FromStream(fromFile, true);
  245. //原图宽高均小于模版,不作处理,直接保存
  246. if ((initImage.Width <= targetWidth) && (initImage.Height <= targetHeight))
  247. {
  248. //文字水印
  249. if (!string.IsNullOrEmpty(watermarkText))
  250. {
  251. using var gWater = Graphics.FromImage(initImage);
  252. Font fontWater = new Font("黑体", 10);
  253. Brush brushWater = new SolidBrush(Color.White);
  254. gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
  255. gWater.Dispose();
  256. }
  257. //透明图片水印
  258. if (!string.IsNullOrEmpty(watermarkImage))
  259. {
  260. if (File.Exists(watermarkImage))
  261. {
  262. using var wrImage = Image.FromFile(watermarkImage);
  263. //水印绘制条件:原始图片宽高均大于或等于水印图片
  264. if ((initImage.Width >= wrImage.Width) && (initImage.Height >= wrImage.Height))
  265. {
  266. Graphics gWater = Graphics.FromImage(initImage);
  267. //透明属性
  268. ImageAttributes imgAttributes = new ImageAttributes();
  269. ColorMap colorMap = new ColorMap();
  270. colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
  271. colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
  272. ColorMap[] remapTable = { colorMap };
  273. imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
  274. float[][] colorMatrixElements =
  275. {
  276. new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
  277. new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
  278. new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
  279. new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
  280. new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
  281. };
  282. ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
  283. imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
  284. gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
  285. gWater.Dispose();
  286. }
  287. wrImage.Dispose();
  288. }
  289. }
  290. //保存
  291. initImage.Save(savePath, initImage.RawFormat);
  292. }
  293. else
  294. {
  295. //缩略图宽、高计算
  296. double newWidth = initImage.Width;
  297. double newHeight = initImage.Height;
  298. //宽大于高或宽等于高(横图或正方)
  299. if ((initImage.Width > initImage.Height) || (initImage.Width == initImage.Height))
  300. {
  301. //如果宽大于模版
  302. if (initImage.Width > targetWidth)
  303. {
  304. //宽按模版,高按比例缩放
  305. newWidth = targetWidth;
  306. newHeight = initImage.Height * (targetWidth / initImage.Width);
  307. }
  308. }
  309. //高大于宽(竖图)
  310. else
  311. {
  312. //如果高大于模版
  313. if (initImage.Height > targetHeight)
  314. {
  315. //高按模版,宽按比例缩放
  316. newHeight = targetHeight;
  317. newWidth = initImage.Width * (targetHeight / initImage.Height);
  318. }
  319. }
  320. //生成新图
  321. //新建一个bmpp图片
  322. using Image newImage = new Bitmap((int)newWidth, (int)newHeight);
  323. //新建一个画板
  324. using Graphics newG = Graphics.FromImage(newImage);
  325. //设置质量
  326. newG.InterpolationMode = InterpolationMode.HighQualityBicubic;
  327. newG.SmoothingMode = SmoothingMode.HighQuality;
  328. //置背景色
  329. newG.Clear(Color.White);
  330. //画图
  331. newG.DrawImage(initImage, new Rectangle(0, 0, newImage.Width, newImage.Height), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel);
  332. //文字水印
  333. if (!string.IsNullOrEmpty(watermarkText))
  334. {
  335. using var gWater = Graphics.FromImage(newImage);
  336. Font fontWater = new Font("微软雅黑", 10);
  337. Brush brushWater = new SolidBrush(Color.White);
  338. gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
  339. gWater.Dispose();
  340. }
  341. //透明图片水印
  342. if (!string.IsNullOrEmpty(watermarkImage))
  343. {
  344. if (File.Exists(watermarkImage))
  345. {
  346. using Image wrImage = Image.FromFile(watermarkImage);
  347. //水印绘制条件:原始图片宽高均大于或等于水印图片
  348. if ((newImage.Width >= wrImage.Width) && (newImage.Height >= wrImage.Height))
  349. {
  350. Graphics gWater = Graphics.FromImage(newImage);
  351. //透明属性
  352. ImageAttributes imgAttributes = new ImageAttributes();
  353. ColorMap colorMap = new ColorMap
  354. {
  355. OldColor = Color.FromArgb(255, 0, 255, 0),
  356. NewColor = Color.FromArgb(0, 0, 0, 0)
  357. };
  358. ColorMap[] remapTable = { colorMap };
  359. imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
  360. float[][] colorMatrixElements =
  361. {
  362. new[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
  363. new[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
  364. new[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
  365. new[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, //透明度:0.5
  366. new[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
  367. };
  368. ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
  369. imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
  370. gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
  371. gWater.Dispose();
  372. }
  373. }
  374. }
  375. //保存缩略图
  376. newImage.Save(savePath, initImage.RawFormat);
  377. }
  378. }
  379. #endregion 等比缩放
  380. #region 判断文件类型是否为WEB格式图片
  381. /// <summary>
  382. /// 判断文件类型是否为WEB格式图片
  383. /// (注:JPG,GIF,BMP,PNG)
  384. /// </summary>
  385. /// <param name="contentType">HttpPostedFile.ContentType</param>
  386. /// <returns>是否为WEB格式图片</returns>
  387. public static bool IsWebImage(string contentType)
  388. {
  389. return contentType == "image/pjpeg" || contentType == "image/jpeg" || contentType == "image/gif" || contentType == "image/bmpp" || contentType == "image/png";
  390. }
  391. #endregion 判断文件类型是否为WEB格式图片
  392. #region 裁剪图片
  393. /// <summary>
  394. /// 裁剪图片 -- 用GDI+
  395. /// </summary>
  396. /// <param name="b">原始Bitmap</param>
  397. /// <param name="rec">裁剪区域</param>
  398. /// <returns>剪裁后的Bitmap</returns>
  399. public static Bitmap CutImage(this Bitmap b, Rectangle rec)
  400. {
  401. int w = b.Width;
  402. int h = b.Height;
  403. if (rec.X >= w || rec.Y >= h)
  404. {
  405. return null;
  406. }
  407. if (rec.X + rec.Width > w)
  408. {
  409. rec.Width = w - rec.X;
  410. }
  411. if (rec.Y + rec.Height > h)
  412. {
  413. rec.Height = h - rec.Y;
  414. }
  415. try
  416. {
  417. var bmppOut = new Bitmap(rec.Width, rec.Height, PixelFormat.Format24bppRgb);
  418. using var g = Graphics.FromImage(bmppOut);
  419. g.DrawImage(b, new Rectangle(0, 0, rec.Width, rec.Height), new Rectangle(rec.X, rec.Y, rec.Width, rec.Height), GraphicsUnit.Pixel);
  420. return bmppOut;
  421. }
  422. catch (Exception)
  423. {
  424. return null;
  425. }
  426. }
  427. #endregion 裁剪图片
  428. #region 缩放图片
  429. /// <summary>
  430. /// Resize图片
  431. /// </summary>
  432. /// <param name="bmpp">原始Bitmap </param>
  433. /// <param name="newWidth">新的宽度</param>
  434. /// <param name="newHeight">新的高度</param>
  435. /// <returns>处理以后的图片</returns>
  436. public static Bitmap ResizeImage(this Bitmap bmpp, int newWidth, int newHeight)
  437. {
  438. try
  439. {
  440. var b = new Bitmap(newWidth, newHeight);
  441. using var g = Graphics.FromImage(b);
  442. // 插值算法的质量
  443. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  444. g.DrawImage(bmpp, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, bmpp.Width, bmpp.Height), GraphicsUnit.Pixel);
  445. return b;
  446. }
  447. catch (Exception)
  448. {
  449. return null;
  450. }
  451. }
  452. #endregion 缩放图片
  453. #region 裁剪并缩放
  454. /// <summary>
  455. /// 裁剪并缩放
  456. /// </summary>
  457. /// <param name="bmpp">原始图片</param>
  458. /// <param name="rec">裁剪的矩形区域</param>
  459. /// <param name="newWidth">新的宽度</param>
  460. /// <param name="newHeight">新的高度</param>
  461. /// <returns>处理以后的图片</returns>
  462. public static Bitmap CutAndResize(this Bitmap bmpp, Rectangle rec, int newWidth, int newHeight) => bmpp.CutImage(rec).ResizeImage(newWidth, newHeight);
  463. #endregion 裁剪并缩放
  464. #region 无损压缩图片
  465. /// <summary>
  466. /// 无损压缩图片
  467. /// </summary>
  468. /// <param name="sFile">原图片地址</param>
  469. /// <param name="dFile">压缩后保存图片地址</param>
  470. /// <param name="quality">压缩质量(数字越小压缩率越高)1-100</param>
  471. /// <param name="size">压缩后图片的最大大小</param>
  472. /// <param name="sfsc">是否是第一次调用</param>
  473. /// <returns></returns>
  474. public static bool CompressImage(string sFile, string dFile, byte quality = 90, int size = 1024, bool sfsc = true)
  475. {
  476. //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  477. var firstFileInfo = new FileInfo(sFile);
  478. if (sfsc && firstFileInfo.Length < size * 1024)
  479. {
  480. firstFileInfo.CopyTo(dFile);
  481. return true;
  482. }
  483. using Image iSource = Image.FromFile(sFile);
  484. int dHeight = iSource.Height;
  485. int dWidth = iSource.Width;
  486. int sW, sH;
  487. //按比例缩放
  488. Size temSize = new Size(iSource.Width, iSource.Height);
  489. if (temSize.Width > dHeight || temSize.Width > dWidth)
  490. {
  491. if (temSize.Width * dHeight > temSize.Width * dWidth)
  492. {
  493. sW = dWidth;
  494. sH = dWidth * temSize.Height / temSize.Width;
  495. }
  496. else
  497. {
  498. sH = dHeight;
  499. sW = temSize.Width * dHeight / temSize.Height;
  500. }
  501. }
  502. else
  503. {
  504. sW = temSize.Width;
  505. sH = temSize.Height;
  506. }
  507. using Bitmap bmpp = new Bitmap(dWidth, dHeight);
  508. using Graphics g = Graphics.FromImage(bmpp);
  509. g.Clear(Color.WhiteSmoke);
  510. g.CompositingQuality = CompositingQuality.HighQuality;
  511. g.SmoothingMode = SmoothingMode.HighQuality;
  512. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  513. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  514. //以下代码为保存图片时,设置压缩质量
  515. using var ep = new EncoderParameters();
  516. using var eParam = new EncoderParameter(Encoder.Quality, new long[] { quality });
  517. ep.Param[0] = eParam;
  518. try
  519. {
  520. ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
  521. ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
  522. if (jpegIcIinfo != null)
  523. {
  524. bmpp.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
  525. FileInfo fi = new FileInfo(dFile);
  526. if (fi.Length > 1024 * size && quality > 10)
  527. {
  528. quality -= 10;
  529. CompressImage(sFile, dFile, quality, size, false);
  530. }
  531. }
  532. else
  533. {
  534. bmpp.Save(dFile, iSource.RawFormat);
  535. }
  536. return true;
  537. }
  538. catch
  539. {
  540. return false;
  541. }
  542. }
  543. /// <summary>
  544. /// 无损压缩图片
  545. /// </summary>
  546. /// <param name="src">原图片文件流</param>
  547. /// <param name="dest">压缩后图片文件流</param>
  548. /// <param name="quality">压缩质量(数字越小压缩率越高)1-100</param>
  549. /// <param name="size">压缩后图片的最大大小</param>
  550. /// <param name="sfsc">是否是第一次调用</param>
  551. /// <returns></returns>
  552. public static bool CompressImage(Stream src, Stream dest, byte quality = 90, int size = 1024, bool sfsc = true)
  553. {
  554. //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  555. if (sfsc && src.Length < size * 1024)
  556. {
  557. src.CopyTo(dest);
  558. return true;
  559. }
  560. using Image iSource = Image.FromStream(src);
  561. int dHeight = iSource.Height;
  562. int dWidth = iSource.Width;
  563. int sW, sH;
  564. //按比例缩放
  565. Size temSize = new Size(iSource.Width, iSource.Height);
  566. if (temSize.Width > dHeight || temSize.Width > dWidth)
  567. {
  568. if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
  569. {
  570. sW = dWidth;
  571. sH = (dWidth * temSize.Height) / temSize.Width;
  572. }
  573. else
  574. {
  575. sH = dHeight;
  576. sW = (temSize.Width * dHeight) / temSize.Height;
  577. }
  578. }
  579. else
  580. {
  581. sW = temSize.Width;
  582. sH = temSize.Height;
  583. }
  584. using Bitmap bmpp = new Bitmap(dWidth, dHeight);
  585. using Graphics g = Graphics.FromImage(bmpp);
  586. g.Clear(Color.WhiteSmoke);
  587. g.CompositingQuality = CompositingQuality.HighQuality;
  588. g.SmoothingMode = SmoothingMode.HighQuality;
  589. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  590. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  591. //以下代码为保存图片时,设置压缩质量
  592. using var ep = new EncoderParameters();
  593. using var eParam = new EncoderParameter(Encoder.Quality, new long[] { quality });
  594. ep.Param[0] = eParam;
  595. try
  596. {
  597. ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders();
  598. ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
  599. if (jpegIcIinfo != null)
  600. {
  601. bmpp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
  602. if (dest.Length > 1024 * size && quality > 10)
  603. {
  604. quality -= 10;
  605. CompressImage(src, dest, quality, size, false);
  606. }
  607. }
  608. else
  609. {
  610. bmpp.Save(dest, iSource.RawFormat);
  611. }
  612. return true;
  613. }
  614. catch
  615. {
  616. return false;
  617. }
  618. }
  619. #endregion 无损压缩图片
  620. #region 缩略图
  621. /// <summary>
  622. /// 生成缩略图
  623. /// </summary>
  624. /// <param name="originalImage">原图</param>
  625. /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
  626. /// <param name="width">缩略图宽度</param>
  627. /// <param name="height">缩略图高度</param>
  628. /// <param name="mode">生成缩略图的方式</param>
  629. public static void MakeThumbnail(this Image originalImage, string thumbnailPath, int width, int height, ThumbnailCutMode mode)
  630. {
  631. using var bitmap = MakeThumbnail(originalImage, width, height, mode);
  632. bitmap.Save(thumbnailPath, originalImage.RawFormat);
  633. }
  634. /// <summary>
  635. /// 生成缩略图
  636. /// </summary>
  637. /// <param name="originalImage">原图</param>
  638. /// <param name="width">缩略图宽度</param>
  639. /// <param name="height">缩略图高度</param>
  640. /// <param name="mode">生成缩略图的方式</param>
  641. public static Image MakeThumbnail(this Image originalImage, int width, int height, ThumbnailCutMode mode)
  642. {
  643. int towidth = width;
  644. int toheight = height;
  645. int x = 0;
  646. int y = 0;
  647. int ow = originalImage.Width;
  648. int oh = originalImage.Height;
  649. switch (mode)
  650. {
  651. case ThumbnailCutMode.Fixed: //指定高宽缩放(可能变形)
  652. break;
  653. case ThumbnailCutMode.LockWidth: //指定宽,高按比例
  654. toheight = originalImage.Height * width / originalImage.Width;
  655. break;
  656. case ThumbnailCutMode.LockHeight: //指定高,宽按比例
  657. towidth = originalImage.Width * height / originalImage.Height;
  658. break;
  659. case ThumbnailCutMode.LockHeightAndWidth: //指定高,宽按比例
  660. towidth = originalImage.Width * height / originalImage.Height;
  661. towidth = towidth > width ? width : towidth;
  662. toheight = originalImage.Height * towidth / originalImage.Width;
  663. toheight = toheight > height ? height : toheight;
  664. towidth = originalImage.Width * toheight / originalImage.Height;
  665. break;
  666. case ThumbnailCutMode.Cut: //指定高宽裁减(不变形)
  667. if (originalImage.Width / (double)originalImage.Height > towidth / (double)toheight)
  668. {
  669. oh = originalImage.Height;
  670. ow = originalImage.Height * towidth / toheight;
  671. y = 0;
  672. x = (originalImage.Width - ow) / 2;
  673. }
  674. else
  675. {
  676. ow = originalImage.Width;
  677. oh = originalImage.Width * height / towidth;
  678. x = 0;
  679. y = (originalImage.Height - oh) / 2;
  680. }
  681. break;
  682. }
  683. //新建一个bmpp图片
  684. Image bitmap = new Bitmap(towidth, toheight);
  685. //新建一个画板
  686. using Graphics g = Graphics.FromImage(bitmap);
  687. //设置高质量插值法
  688. g.InterpolationMode = InterpolationMode.High;
  689. //设置高质量,低速度呈现平滑程度
  690. g.SmoothingMode = SmoothingMode.HighQuality;
  691. //清空画布并以透明背景色填充
  692. g.Clear(Color.Transparent);
  693. //在指定位置并且按指定大小绘制原图片的指定部分
  694. //第一个:对哪张图片进行操作。
  695. //二:画多么大。
  696. //三:画那块区域。
  697. g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
  698. return bitmap;
  699. }
  700. #endregion 缩略图
  701. #region 调整光暗
  702. /// <summary>
  703. /// 调整光暗
  704. /// </summary>
  705. /// <param name="source">原始图片</param>
  706. /// <param name="width">原始图片的长度</param>
  707. /// <param name="height">原始图片的高度</param>
  708. /// <param name="val">增加或减少的光暗值</param>
  709. public static Bitmap LDPic(this Bitmap source, int width, int height, int val)
  710. {
  711. Bitmap bmp = new Bitmap(width, height); //初始化一个记录经过处理后的图片对象
  712. for (int x = 0; x < width; x++)
  713. {
  714. for (int y = 0; y < height; y++)
  715. {
  716. var pixel = source.GetPixel(x, y);
  717. var resultR = pixel.R + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
  718. var resultG = pixel.G + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
  719. var resultB = pixel.B + val; //x、y是循环次数,后面三个是记录红绿蓝三个值的
  720. bmp.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB)); //绘图
  721. }
  722. }
  723. return bmp;
  724. }
  725. #endregion 调整光暗
  726. #region 反色处理
  727. /// <summary>
  728. /// 反色处理
  729. /// </summary>
  730. /// <param name="source">原始图片</param>
  731. /// <param name="width">原始图片的长度</param>
  732. /// <param name="height">原始图片的高度</param>
  733. public static Bitmap RePic(this Bitmap source, int width, int height)
  734. {
  735. var bmp = new Bitmap(width, height); //初始化一个记录处理后的图片的对象
  736. for (var x = 0; x < width; x++)
  737. {
  738. for (var y = 0; y < height; y++)
  739. {
  740. var pixel = source.GetPixel(x, y);
  741. var resultR = 255 - pixel.R;
  742. var resultG = 255 - pixel.G;
  743. var resultB = 255 - pixel.B;
  744. bmp.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB)); //绘图
  745. }
  746. }
  747. return bmp;
  748. }
  749. #endregion 反色处理
  750. #region 浮雕处理
  751. /// <summary>
  752. /// 浮雕处理
  753. /// </summary>
  754. /// <param name="oldBitmap">原始图片</param>
  755. /// <param name="width">原始图片的长度</param>
  756. /// <param name="height">原始图片的高度</param>
  757. public static Bitmap Relief(this Bitmap oldBitmap, int width, int height)
  758. {
  759. var newBitmap = new Bitmap(width, height);
  760. for (int x = 0; x < width - 1; x++)
  761. {
  762. for (int y = 0; y < height - 1; y++)
  763. {
  764. var color1 = oldBitmap.GetPixel(x, y);
  765. var color2 = oldBitmap.GetPixel(x + 1, y + 1);
  766. var r = Math.Abs(color1.R - color2.R + 128);
  767. var g = Math.Abs(color1.G - color2.G + 128);
  768. var b = Math.Abs(color1.B - color2.B + 128);
  769. if (r > 255) r = 255;
  770. if (r < 0) r = 0;
  771. if (g > 255) g = 255;
  772. if (g < 0) g = 0;
  773. if (b > 255) b = 255;
  774. if (b < 0) b = 0;
  775. newBitmap.SetPixel(x, y, Color.FromArgb(r, g, b));
  776. }
  777. }
  778. return newBitmap;
  779. }
  780. #endregion 浮雕处理
  781. #region 拉伸图片
  782. /// <summary>
  783. /// 拉伸图片
  784. /// </summary>
  785. /// <param name="bmpp">原始图片</param>
  786. /// <param name="newW">新的宽度</param>
  787. /// <param name="newH">新的高度</param>
  788. public static async Task<Bitmap> ResizeImageAsync(this Bitmap bmpp, int newW, int newH)
  789. {
  790. try
  791. {
  792. Bitmap bap = new Bitmap(newW, newH);
  793. return await Task.Run(() =>
  794. {
  795. using Graphics g = Graphics.FromImage(bap);
  796. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  797. g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
  798. return bap;
  799. }).ConfigureAwait(false);
  800. }
  801. catch (Exception)
  802. {
  803. return null;
  804. }
  805. }
  806. #endregion 拉伸图片
  807. #region 滤色处理
  808. /// <summary>
  809. /// 滤色处理
  810. /// </summary>
  811. /// <param name="source">原始图片</param>
  812. /// <param name="width">原始图片的长度</param>
  813. /// <param name="height">原始图片的高度</param>
  814. public static Bitmap FilPic(this Bitmap source, int width, int height)
  815. {
  816. var bmp = new Bitmap(width, height);
  817. for (var x = 0; x < width; x++)
  818. {
  819. int y;
  820. for (y = 0; y < height; y++)
  821. {
  822. var pixel = source.GetPixel(x, y);
  823. bmp.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B)); //绘图
  824. }
  825. }
  826. return bmp;
  827. }
  828. #endregion 滤色处理
  829. #region 左右翻转
  830. /// <summary>
  831. /// 左右翻转
  832. /// </summary>
  833. /// <param name="source">原始图片</param>
  834. /// <param name="width">原始图片的长度</param>
  835. /// <param name="height">原始图片的高度</param>
  836. public static Bitmap RevPicLR(this Bitmap source, int width, int height)
  837. {
  838. var bmp = new Bitmap(width, height);
  839. //x,y是循环次数,z是用来记录像素点的x坐标的变化的
  840. for (var y = height - 1; y >= 0; y--)
  841. {
  842. int x; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
  843. int z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
  844. for (x = width - 1, z = 0; x >= 0; x--)
  845. {
  846. var pixel = source.GetPixel(x, y);
  847. bmp.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
  848. }
  849. }
  850. return bmp;
  851. }
  852. #endregion 左右翻转
  853. #region 上下翻转
  854. /// <summary>
  855. /// 上下翻转
  856. /// </summary>
  857. /// <param name="source">原始图片</param>
  858. /// <param name="width">原始图片的长度</param>
  859. /// <param name="height">原始图片的高度</param>
  860. public static Bitmap RevPicUD(this Bitmap source, int width, int height)
  861. {
  862. var bmp = new Bitmap(width, height);
  863. for (var x = 0; x < width; x++)
  864. {
  865. int y;
  866. int z;
  867. for (y = height - 1, z = 0; y >= 0; y--)
  868. {
  869. var pixel = source.GetPixel(x, y);
  870. bmp.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B)); //绘图
  871. }
  872. }
  873. return bmp;
  874. }
  875. #endregion 上下翻转
  876. #region 灰度化
  877. /// <summary>
  878. /// 色彩灰度化
  879. /// </summary>
  880. /// <param name="c">输入颜色</param>
  881. /// <returns>输出颜色</returns>
  882. public static Color Gray(this Color c)
  883. {
  884. int rgb = Convert.ToInt32(0.3 * c.R + 0.59 * c.G + 0.11 * c.B);
  885. return Color.FromArgb(rgb, rgb, rgb);
  886. }
  887. #endregion 灰度化
  888. #region 转换为黑白图片
  889. /// <summary>
  890. /// 转换为黑白图片
  891. /// </summary>
  892. /// <param name="source">要进行处理的图片</param>
  893. /// <param name="width">图片的长度</param>
  894. /// <param name="height">图片的高度</param>
  895. public static Bitmap BWPic(this Bitmap source, int width, int height)
  896. {
  897. var bmp = new Bitmap(width, height);
  898. for (var x = 0; x < width; x++)
  899. {
  900. for (var y = 0; y < height; y++)
  901. {
  902. var pixel = source.GetPixel(x, y);
  903. var result = (pixel.R + pixel.G + pixel.B) / 3; //记录处理后的像素值
  904. bmp.SetPixel(x, y, Color.FromArgb(result, result, result));
  905. }
  906. }
  907. return bmp;
  908. }
  909. #endregion 转换为黑白图片
  910. #region 获取图片中的各帧
  911. /// <summary>
  912. /// 获取gif图片中的各帧
  913. /// </summary>
  914. /// <param name="gif">源gif</param>
  915. /// <param name="pSavedPath">保存路径</param>
  916. public static void GetFrames(this Image gif, string pSavedPath)
  917. {
  918. var fd = new FrameDimension(gif.FrameDimensionsList[0]);
  919. int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
  920. for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
  921. {
  922. gif.SelectActiveFrame(fd, i);
  923. gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
  924. }
  925. }
  926. #endregion 获取图片中的各帧
  927. /// <summary>
  928. /// 将dataUri保存为图片
  929. /// </summary>
  930. /// <param name="source">dataUri数据源</param>
  931. /// <returns></returns>
  932. /// <exception cref="Exception">操作失败。</exception>
  933. public static Bitmap SaveDataUriAsImageFile(this string source)
  934. {
  935. string strbase64 = source.Substring(source.IndexOf(',') + 1).Trim('\0');
  936. byte[] arr = Convert.FromBase64String(strbase64);
  937. using var ms = new MemoryStream(arr);
  938. using var bmpp = new Bitmap(ms);
  939. //新建第二个bitmap类型的bmpp2变量。
  940. var bmpp2 = new Bitmap(bmpp, bmpp.Width, bmpp.Height);
  941. using var draw = Graphics.FromImage(bmpp2);
  942. draw.DrawImage(bmpp, 0, 0, bmpp.Width, bmpp.Height);
  943. return bmpp2;
  944. }
  945. }
  946. }