星火微课系统客户端
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ImageHelper.cs 19KB

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