星火微课系统客户端
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 18KB

4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
4 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. string TempPath=FileToolsCommon.GetFileAbsolutePath("/temp/Screenshot/");
  157. FileToolsCommon.CreateDirectory(TempPath);
  158. return TempPath;
  159. }
  160. #endregion 截图统一方法
  161. #region 图片压缩
  162. /// <summary>
  163. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  164. /// </summary>
  165. /// <param name="srcBitMap">传入的Bitmap对象</param>
  166. /// <param name="destFile">压缩后的图片保存路径</param>
  167. /// <param name="level">压缩等级,-1为config配置的值,0到100,0 最差质量,100 最佳</param>
  168. public static void Compress(Bitmap srcBitMap, string destFile, long level)
  169. {
  170. if (level <= -1)
  171. {
  172. int ImageCompressionLevel = int.Parse(FileToolsCommon.GetConfigValue("ImageCompressionLevel"));
  173. level = ImageCompressionLevel;
  174. }
  175. Stream s = new FileStream(destFile, FileMode.Create);
  176. Compress(srcBitMap, s, level);
  177. s.Close();
  178. }
  179. /// <summary>
  180. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  181. /// </summary>
  182. /// <param name="srcBitmap">传入的Bitmap对象</param>
  183. /// <param name="destStream">压缩后的Stream对象</param>
  184. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  185. public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
  186. {
  187. ImageCodecInfo myImageCodecInfo;
  188. System.Drawing.Imaging.Encoder myEncoder;
  189. EncoderParameter myEncoderParameter;
  190. EncoderParameters myEncoderParameters;
  191. //获取表示jpeg编解码器的imagecodecinfo对象
  192. myImageCodecInfo = GetEncoderInfo("image/jpeg");
  193. myEncoder = System.Drawing.Imaging.Encoder.Quality;
  194. myEncoderParameters = new EncoderParameters(1);
  195. myEncoderParameter = new EncoderParameter(myEncoder, level);
  196. myEncoderParameters.Param[0] = myEncoderParameter;
  197. srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
  198. }
  199. /// <summary>
  200. /// 获取解码器 创建人:赵耀 创建时间2020年8月11日
  201. /// </summary>
  202. /// <param name="mimeType"></param>
  203. /// <returns></returns>
  204. private static ImageCodecInfo GetEncoderInfo(string mimeType)
  205. {
  206. int j;
  207. ImageCodecInfo[] encoders;
  208. encoders = ImageCodecInfo.GetImageEncoders();
  209. for (j = 0; j < encoders.Length; ++j)
  210. {
  211. if (encoders[j].MimeType == mimeType)
  212. {
  213. return encoders[j];
  214. }
  215. }
  216. return null;
  217. }
  218. /// <summary>
  219. /// 压缩图片 -测试方法 待完善 暂无用
  220. /// </summary>
  221. /// <param name="_bitmap">原图片</param>
  222. /// <param name="dFile">压缩后保存图片地址</param>
  223. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  224. /// <param name="size">压缩后图片的最大大小</param>
  225. /// <param name="sfsc">是否是第一次调用</param>
  226. /// <returns></returns>
  227. public static bool CompressImage(Bitmap _bitmap, string dFile, int flag = 90, int size = 300)
  228. {
  229. ////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  230. //FileInfo firstFileInfo = new FileInfo(sFile);
  231. //if (sfsc == true && firstFileInfo.Length < size * 1024)
  232. //{
  233. // firstFileInfo.CopyTo(dFile);
  234. // return true;
  235. //}
  236. //Image iSource = Image.FromFile(sFile);
  237. Image iSource = _bitmap;
  238. ImageFormat tFormat = iSource.RawFormat;
  239. int dHeight = iSource.Height / 2;
  240. int dWidth = iSource.Width / 2;
  241. int sW, sH;
  242. //按比例缩放
  243. System.Drawing.Size tem_size = new System.Drawing.Size(iSource.Width, iSource.Height);
  244. if (tem_size.Width > dHeight || tem_size.Width > dWidth)
  245. {
  246. if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
  247. {
  248. sW = dWidth;
  249. sH = (dWidth * tem_size.Height) / tem_size.Width;
  250. }
  251. else
  252. {
  253. sH = dHeight;
  254. sW = (tem_size.Width * dHeight) / tem_size.Height;
  255. }
  256. }
  257. else
  258. {
  259. sW = tem_size.Width;
  260. sH = tem_size.Height;
  261. }
  262. Bitmap ob = new Bitmap(dWidth, dHeight);
  263. Graphics g = Graphics.FromImage(ob);
  264. g.Clear(System.Drawing.Color.WhiteSmoke);
  265. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  266. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  267. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  268. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  269. g.Dispose();
  270. //以下代码为保存图片时,设置压缩质量
  271. EncoderParameters ep = new EncoderParameters();
  272. long[] qy = new long[1];
  273. qy[0] = flag;//设置压缩的比例1-100
  274. EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
  275. ep.Param[0] = eParam;
  276. try
  277. {
  278. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
  279. ImageCodecInfo jpegICIinfo = null;
  280. for (int x = 0; x < arrayICI.Length; x++)
  281. {
  282. if (arrayICI[x].FormatDescription.Equals("JPEG"))
  283. {
  284. jpegICIinfo = arrayICI[x];
  285. break;
  286. }
  287. }
  288. if (jpegICIinfo != null)
  289. {
  290. if (flag > 0)
  291. {
  292. ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
  293. FileInfo fi = new FileInfo(dFile);
  294. if (fi.Length > 1024 * size)
  295. {
  296. flag -= 10;
  297. CompressImage(_bitmap, dFile, flag, size);
  298. }
  299. }
  300. //ob.Save(dFile, jpegICIinfo, ep);
  301. //FileInfo fi = new FileInfo(dFile);
  302. //bool IsAgain = false;
  303. //if (fi.Length > 1024 * size)
  304. //{
  305. // fi.CopyTo(dFile + fi.Length);
  306. // fi.Delete();
  307. // Bitmap newbitmap = ReadImageFile(dFile + fi.Length);
  308. // CompressImage(newbitmap, dFile, flag, size);
  309. // FileToolsCommon.DeleteFile(dFile + fi.Length);
  310. //}
  311. }
  312. else
  313. {
  314. ob.Save(dFile, tFormat);
  315. }
  316. return true;
  317. }
  318. catch
  319. {
  320. return false;
  321. }
  322. finally
  323. {
  324. iSource.Dispose();
  325. ob.Dispose();
  326. }
  327. }
  328. #endregion 图片压缩
  329. #region 截屏指定UI控件
  330. /// <summary>
  331. /// 保存图片
  332. /// </summary>
  333. /// <param name="ui">需要截图的UI控件</param>
  334. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  335. /// <param name="width">保存宽</param>
  336. /// <param name="height">保存高</param>
  337. public static void SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height)
  338. {
  339. try
  340. {
  341. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  342. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d,
  343. PixelFormats.Pbgra32);
  344. bmp.Render(ui);
  345. BitmapEncoder encoder = new PngBitmapEncoder();
  346. encoder.Frames.Add(BitmapFrame.Create(bmp));
  347. encoder.Save(fs);
  348. fs.Close();
  349. new Thread(new ThreadStart(new Action(() =>
  350. {
  351. Bitmap bitmap = CutImageWhitePart(filePathName);
  352. FileToolsCommon.DeleteFile(filePathName);
  353. bitmap.Save(filePathName);
  354. }))).Start();
  355. }
  356. catch (Exception ex)
  357. {
  358. LogHelper.WriteErrLog("【UI生成图片】(SaveUIToImage)" + ex.Message, ex);
  359. //Console.WriteLine(ex.Message);
  360. }
  361. }
  362. #endregion
  363. #region 去掉白边
  364. /// <summary>
  365. /// 裁剪图片(去掉白边)
  366. /// </summary>
  367. /// <param name="FilePath"></param>
  368. public static Bitmap CutImageWhitePart(string FilePath)
  369. {
  370. Bitmap bmp = new Bitmap(FilePath);
  371. //上左右下
  372. int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
  373. //寻找最上面的标线,从左(0)到右,从上(0)到下
  374. for (int i = 0; i < bmp.Height; i++)//行
  375. {
  376. bool find = false;
  377. for (int j = 0; j < bmp.Width; j++)//列
  378. {
  379. System.Drawing.Color c = bmp.GetPixel(j, i);
  380. if (!IsWhite(c))
  381. {
  382. top = i;
  383. find = true;
  384. break;
  385. }
  386. }
  387. if (find)
  388. break;
  389. }
  390. //寻找最左边的标线,从上(top位)到下,从左到右
  391. for (int i = 0; i < bmp.Width; i++)//列
  392. {
  393. bool find = false;
  394. for (int j = top; j < bmp.Height; j++)//行
  395. {
  396. System.Drawing.Color c = bmp.GetPixel(i, j);
  397. if (!IsWhite(c))
  398. {
  399. left = i;
  400. find = true;
  401. break;
  402. }
  403. }
  404. if (find)
  405. break;
  406. }
  407. //寻找最下边标线,从下到上,从左到右
  408. for (int i = bmp.Height - 1; i >= 0; i--)//行
  409. {
  410. bool find = false;
  411. for (int j = left; j < bmp.Width; j++)//列
  412. {
  413. System.Drawing.Color c = bmp.GetPixel(j, i);
  414. if (!IsWhite(c))
  415. {
  416. bottom = i;
  417. find = true;
  418. break;
  419. }
  420. }
  421. if (find)
  422. break;
  423. }
  424. //寻找最右边的标线,从上到下,从右往左
  425. for (int i = bmp.Width - 1; i >= 0; i--)//列
  426. {
  427. bool find = false;
  428. for (int j = 0; j <= bottom; j++)//行
  429. {
  430. System.Drawing.Color c = bmp.GetPixel(i, j);
  431. if (!IsWhite(c))
  432. {
  433. right = i;
  434. find = true;
  435. break;
  436. }
  437. }
  438. if (find)
  439. break;
  440. }
  441. //克隆位图对象的一部分。
  442. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, right - left, bottom - top);
  443. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  444. bmp.Dispose();
  445. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  446. return cloneBitmap;
  447. }
  448. /// <summary>
  449. /// 判断是否白色和纯透明色(10点的容差)
  450. /// </summary>
  451. public static bool IsWhite(System.Drawing.Color c)
  452. {
  453. //纯透明也是白色,RGB都为255为纯白
  454. if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
  455. return true;
  456. return false;
  457. }
  458. #endregion
  459. }
  460. }