ImageUtilities.cs 44 KB

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