ImageUtilities.cs 42 KB

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