ImageUtilities.cs 44 KB

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