星火微课系统客户端
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ImageHelper.cs 19KB

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