星火微课系统客户端
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ImageHelper.cs 21KB

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