星火微课系统客户端
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ImageHelper.cs 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Imaging;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Windows;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Imaging;
  10. namespace Common.system
  11. {
  12. /// <summary>
  13. /// 图片帮助类
  14. /// 创建人:赵耀
  15. /// 创建时间:2018年11月1日
  16. /// </summary>
  17. public class ImageHelper
  18. {
  19. /// <summary>
  20. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  21. /// </summary>
  22. /// <param name="path">图片位置</param>
  23. /// <returns></returns>
  24. public static Bitmap ReadBitmapFile(string path)
  25. {
  26. try
  27. {
  28. if (File.Exists(path))
  29. {
  30. FileStream fs = File.OpenRead(path); //OpenRead
  31. int filelength = 0;
  32. filelength = (int)fs.Length; //获得文件长度
  33. byte[] image = new byte[filelength]; //建立一个字节数组
  34. fs.Read(image, 0, filelength); //按字节流读取
  35. System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
  36. fs.Close();
  37. Bitmap bit = new Bitmap(result);
  38. return bit;
  39. }
  40. else
  41. {
  42. return null;
  43. }
  44. }
  45. catch (Exception)
  46. {
  47. return null;
  48. }
  49. }
  50. /// <summary>
  51. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  52. /// </summary>
  53. /// <param name="path">图片位置</param>
  54. /// <returns></returns>
  55. public static Image ReadImageFile(string path)
  56. {
  57. try
  58. {
  59. if (File.Exists(path))
  60. {
  61. FileStream fs = File.OpenRead(path); //OpenRead
  62. int filelength = 0;
  63. filelength = (int)fs.Length; //获得文件长度
  64. byte[] image = new byte[filelength]; //建立一个字节数组
  65. fs.Read(image, 0, filelength); //按字节流读取
  66. System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
  67. fs.Close();
  68. return result;
  69. }
  70. else
  71. {
  72. return null;
  73. }
  74. }
  75. catch (Exception)
  76. {
  77. return null;
  78. }
  79. }
  80. #region 获取RGB
  81. private static Bitmap _Bitmap = null;
  82. private static StringBuilder sb = new StringBuilder();
  83. public static string GetRGB(int x, int y)
  84. {
  85. sb = new StringBuilder();
  86. try
  87. {
  88. System.Drawing.Color color = _Bitmap.GetPixel(x, y);
  89. sb.Append("RGB:(");
  90. sb.Append(color.R.ToString());
  91. sb.Append(",");
  92. sb.Append(color.G.ToString());
  93. sb.Append(",");
  94. sb.Append(color.B.ToString());
  95. sb.Append(")");
  96. }
  97. catch (Exception ex)
  98. {
  99. LogHelper.WriteErrLog("ImageHelper(GetRGB)" + ex.Message, ex);
  100. }
  101. return sb.ToString();
  102. }
  103. #endregion 获取RGB
  104. #region 截图统一方法
  105. /// <summary>
  106. /// 截图通用方法 创建人:赵耀 创建时间:2020年8月11日
  107. /// </summary>
  108. /// <param name="ScreenSize">截图的区域,设置new Rectangle(0, 0, 0, 0)为截全屏</param>
  109. /// <param name="ImageSavePath">图片存储路径,为空或null则保存到临时文件夹</param>
  110. /// <param name="IsRetImg">是否返回图片</param>
  111. /// <param name="bitmapimg">图片</param>
  112. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  113. /// <returns></returns>
  114. public static bool GetScreenshot(Rectangle ScreenSize, string ImageSavePath, bool IsRetImg, out BitmapImage bitmapimg, long level = -1)
  115. {
  116. bitmapimg = null;
  117. try
  118. {
  119. System.Drawing.Size bounds = PrimaryScreen.DESKTOP;
  120. if (string.IsNullOrEmpty(ImageSavePath))
  121. {
  122. ImageSavePath = GetTempImagePath();//如果为空则指定临时存储路径
  123. }
  124. double scaleWidth = (bounds.Width * 1.0) / SystemParameters.PrimaryScreenWidth;
  125. double scaleHeight = (bounds.Height * 1.0) / SystemParameters.PrimaryScreenHeight;
  126. int width = bounds.Width;
  127. int height = bounds.Height;
  128. if (ScreenSize.Size != new System.Drawing.Size(0, 0))
  129. {
  130. width = (int)(ScreenSize.Size.Width * scaleWidth);
  131. height = (int)(ScreenSize.Size.Height * scaleHeight);
  132. }
  133. int l = (int)(ScreenSize.X * scaleWidth);
  134. int t = (int)(ScreenSize.Y * scaleHeight);
  135. if (_Bitmap != null)
  136. {
  137. _Bitmap.Dispose();
  138. }
  139. _Bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  140. using (Graphics g = Graphics.FromImage(_Bitmap))
  141. {
  142. g.CopyFromScreen(l, t, 0, 0, _Bitmap.Size, CopyPixelOperation.SourceCopy);
  143. Compress(_Bitmap, ImageSavePath, level);
  144. }
  145. if (IsRetImg)
  146. {
  147. Uri uri = new Uri(ImageSavePath, UriKind.Absolute);
  148. bitmapimg = new BitmapImage(uri);
  149. }
  150. GC.Collect();
  151. return true;
  152. }
  153. catch (Exception ex)
  154. {
  155. LogHelper.WriteErrLog("【截图】(GetBitmapSource)截图失败," + ex.Message, ex);
  156. return false;
  157. }
  158. }
  159. /// <summary>
  160. /// 获取临时图片保存位置
  161. /// </summary>
  162. /// <returns></returns>
  163. public static string GetTempImagePath()
  164. {
  165. TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  166. string TempPath = FileToolsCommon.GetFileAbsolutePath("/temp/Screenshot/");
  167. FileToolsCommon.CreateDirectory(TempPath);
  168. TempPath += Convert.ToInt64(ts.TotalMilliseconds).ToString() + ".jpg";
  169. return TempPath;
  170. }
  171. #endregion 截图统一方法
  172. #region 图片压缩
  173. /// <summary>
  174. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  175. /// </summary>
  176. /// <param name="srcBitMap">传入的Bitmap对象</param>
  177. /// <param name="destFile">压缩后的图片保存路径</param>
  178. /// <param name="level">压缩等级,-1为config配置的值,0到100,0 最差质量,100 最佳</param>
  179. public static void Compress(Bitmap srcBitMap, string destFile, long level)
  180. {
  181. if (level <= -1)
  182. {
  183. int ImageCompressionLevel = int.Parse(FileToolsCommon.GetConfigValue("ImageCompressionLevel"));
  184. level = ImageCompressionLevel;
  185. }
  186. Stream s = new FileStream(destFile, FileMode.Create);
  187. Compress(srcBitMap, s, level);
  188. s.Close();
  189. }
  190. /// <summary>
  191. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  192. /// </summary>
  193. /// <param name="srcBitmap">传入的Bitmap对象</param>
  194. /// <param name="destStream">压缩后的Stream对象</param>
  195. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  196. public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
  197. {
  198. ImageCodecInfo myImageCodecInfo;
  199. System.Drawing.Imaging.Encoder myEncoder;
  200. EncoderParameter myEncoderParameter;
  201. EncoderParameters myEncoderParameters;
  202. //获取表示jpeg编解码器的imagecodecinfo对象
  203. myImageCodecInfo = GetEncoderInfo("image/jpeg");
  204. myEncoder = System.Drawing.Imaging.Encoder.Quality;
  205. myEncoderParameters = new EncoderParameters(1);
  206. myEncoderParameter = new EncoderParameter(myEncoder, level);
  207. myEncoderParameters.Param[0] = myEncoderParameter;
  208. srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
  209. }
  210. /// <summary>
  211. /// 获取解码器 创建人:赵耀 创建时间2020年8月11日
  212. /// </summary>
  213. /// <param name="mimeType"></param>
  214. /// <returns></returns>
  215. private static ImageCodecInfo GetEncoderInfo(string mimeType)
  216. {
  217. int j;
  218. ImageCodecInfo[] encoders;
  219. encoders = ImageCodecInfo.GetImageEncoders();
  220. for (j = 0; j < encoders.Length; ++j)
  221. {
  222. if (encoders[j].MimeType == mimeType)
  223. {
  224. return encoders[j];
  225. }
  226. }
  227. return null;
  228. }
  229. /// <summary>
  230. /// 压缩图片 -测试方法 待完善 暂无用
  231. /// </summary>
  232. /// <param name="_bitmap">原图片</param>
  233. /// <param name="dFile">压缩后保存图片地址</param>
  234. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  235. /// <param name="size">压缩后图片的最大大小</param>
  236. /// <param name="sfsc">是否是第一次调用</param>
  237. /// <returns></returns>
  238. public static bool CompressImage(Bitmap _bitmap, string dFile, int flag = 90, int size = 300)
  239. {
  240. ////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  241. //FileInfo firstFileInfo = new FileInfo(sFile);
  242. //if (sfsc == true && firstFileInfo.Length < size * 1024)
  243. //{
  244. // firstFileInfo.CopyTo(dFile);
  245. // return true;
  246. //}
  247. //Image iSource = Image.FromFile(sFile);
  248. Image iSource = _bitmap;
  249. ImageFormat tFormat = iSource.RawFormat;
  250. int dHeight = iSource.Height / 2;
  251. int dWidth = iSource.Width / 2;
  252. int sW, sH;
  253. //按比例缩放
  254. System.Drawing.Size tem_size = new System.Drawing.Size(iSource.Width, iSource.Height);
  255. if (tem_size.Width > dHeight || tem_size.Width > dWidth)
  256. {
  257. if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
  258. {
  259. sW = dWidth;
  260. sH = (dWidth * tem_size.Height) / tem_size.Width;
  261. }
  262. else
  263. {
  264. sH = dHeight;
  265. sW = (tem_size.Width * dHeight) / tem_size.Height;
  266. }
  267. }
  268. else
  269. {
  270. sW = tem_size.Width;
  271. sH = tem_size.Height;
  272. }
  273. Bitmap ob = new Bitmap(dWidth, dHeight);
  274. Graphics g = Graphics.FromImage(ob);
  275. g.Clear(System.Drawing.Color.WhiteSmoke);
  276. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  277. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  278. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  279. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  280. g.Dispose();
  281. //以下代码为保存图片时,设置压缩质量
  282. EncoderParameters ep = new EncoderParameters();
  283. long[] qy = new long[1];
  284. qy[0] = flag;//设置压缩的比例1-100
  285. EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
  286. ep.Param[0] = eParam;
  287. try
  288. {
  289. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
  290. ImageCodecInfo jpegICIinfo = null;
  291. for (int x = 0; x < arrayICI.Length; x++)
  292. {
  293. if (arrayICI[x].FormatDescription.Equals("JPEG"))
  294. {
  295. jpegICIinfo = arrayICI[x];
  296. break;
  297. }
  298. }
  299. if (jpegICIinfo != null)
  300. {
  301. if (flag > 0)
  302. {
  303. ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
  304. FileInfo fi = new FileInfo(dFile);
  305. if (fi.Length > 1024 * size)
  306. {
  307. flag -= 10;
  308. CompressImage(_bitmap, dFile, flag, size);
  309. }
  310. }
  311. //ob.Save(dFile, jpegICIinfo, ep);
  312. //FileInfo fi = new FileInfo(dFile);
  313. //bool IsAgain = false;
  314. //if (fi.Length > 1024 * size)
  315. //{
  316. // fi.CopyTo(dFile + fi.Length);
  317. // fi.Delete();
  318. // Bitmap newbitmap = ReadImageFile(dFile + fi.Length);
  319. // CompressImage(newbitmap, dFile, flag, size);
  320. // FileToolsCommon.DeleteFile(dFile + fi.Length);
  321. //}
  322. }
  323. else
  324. {
  325. ob.Save(dFile, tFormat);
  326. }
  327. return true;
  328. }
  329. catch
  330. {
  331. return false;
  332. }
  333. finally
  334. {
  335. iSource.Dispose();
  336. ob.Dispose();
  337. }
  338. }
  339. #endregion 图片压缩
  340. #region 截屏指定UI控件
  341. /// <summary>
  342. /// 保存图片
  343. /// </summary>
  344. /// <param name="ui">需要截图的UI控件</param>
  345. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  346. /// <param name="width">保存宽</param>
  347. /// <param name="height">保存高</param>
  348. public static void SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height)
  349. {
  350. try
  351. {
  352. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  353. //在位图中呈现UI元素
  354. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY,
  355. PixelFormats.Pbgra32);
  356. bmp.Render(ui);
  357. BitmapEncoder encoder = new PngBitmapEncoder();
  358. encoder.Frames.Add(BitmapFrame.Create(bmp));
  359. encoder.Save(fs);
  360. fs.Close();
  361. new Thread(new ThreadStart(new Action(() =>
  362. {
  363. Bitmap bitmap = CutImageWhitePart(filePathName);
  364. FileToolsCommon.DeleteFile(filePathName);
  365. bitmap.Save(filePathName);
  366. }))).Start();
  367. }
  368. catch (Exception ex)
  369. {
  370. LogHelper.WriteErrLog("【UI生成图片】(SaveUIToImage)" + ex.Message, ex);
  371. //Console.WriteLine(ex.Message);
  372. }
  373. }
  374. #endregion
  375. #region 去掉白边
  376. /// <summary>
  377. /// 裁剪图片(去掉白边)
  378. /// </summary>
  379. /// <param name="FilePath"></param>
  380. public static Bitmap CutImageWhitePart(string FilePath)
  381. {
  382. Bitmap bmp = new Bitmap(FilePath);
  383. //上左右下
  384. int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
  385. //寻找最上面的标线,从左(0)到右,从上(0)到下
  386. for (int i = 0; i < bmp.Height; i++)//行
  387. {
  388. bool find = false;
  389. for (int j = 0; j < bmp.Width; j++)//列
  390. {
  391. System.Drawing.Color c = bmp.GetPixel(j, i);
  392. if (!IsWhite(c))
  393. {
  394. top = i;
  395. find = true;
  396. break;
  397. }
  398. }
  399. if (find)
  400. {
  401. break;
  402. }
  403. }
  404. //寻找最左边的标线,从上(top位)到下,从左到右
  405. for (int i = 0; i < bmp.Width; i++)//列
  406. {
  407. bool find = false;
  408. for (int j = top; j < bmp.Height; j++)//行
  409. {
  410. System.Drawing.Color c = bmp.GetPixel(i, j);
  411. if (!IsWhite(c))
  412. {
  413. left = i;
  414. find = true;
  415. break;
  416. }
  417. }
  418. if (find)
  419. {
  420. break;
  421. }
  422. }
  423. //寻找最下边标线,从下到上,从左到右
  424. for (int i = bmp.Height - 1; i >= 0; i--)//行
  425. {
  426. bool find = false;
  427. for (int j = left; j < bmp.Width; j++)//列
  428. {
  429. System.Drawing.Color c = bmp.GetPixel(j, i);
  430. if (!IsWhite(c))
  431. {
  432. bottom = i;
  433. find = true;
  434. break;
  435. }
  436. }
  437. if (find)
  438. {
  439. break;
  440. }
  441. }
  442. //寻找最右边的标线,从上到下,从右往左
  443. for (int i = bmp.Width - 1; i >= 0; i--)//列
  444. {
  445. bool find = false;
  446. for (int j = 0; j <= bottom; j++)//行
  447. {
  448. System.Drawing.Color c = bmp.GetPixel(i, j);
  449. if (!IsWhite(c))
  450. {
  451. right = i;
  452. find = true;
  453. break;
  454. }
  455. }
  456. if (find)
  457. {
  458. break;
  459. }
  460. }
  461. if (right - left <= 0)//zxyceshi
  462. {
  463. //克隆位图对象的一部分。
  464. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, 1, bottom - top);
  465. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  466. bmp.Dispose();
  467. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  468. return cloneBitmap;
  469. }
  470. else
  471. {
  472. //克隆位图对象的一部分。
  473. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, right - left, bottom - top);
  474. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  475. bmp.Dispose();
  476. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  477. return cloneBitmap;
  478. }
  479. }
  480. /// <summary>
  481. /// 判断是否白色和纯透明色(10点的容差)
  482. /// </summary>
  483. public static bool IsWhite(System.Drawing.Color c)
  484. {
  485. //纯透明也是白色,RGB都为255为纯白
  486. if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
  487. {
  488. return true;
  489. }
  490. return false;
  491. }
  492. #endregion
  493. }
  494. }