ImageUtilities.cs 44 KB

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