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