星火微课系统客户端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImageHelper.cs 23KB

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