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

ImageHelper.cs 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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. #region 截屏指定UI控件
  81. /// <summary>
  82. /// 保存图片
  83. /// </summary>
  84. /// <param name="ui">需要截图的UI控件</param>
  85. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  86. /// <param name="width">保存宽</param>
  87. /// <param name="height">保存高</param>
  88. public static void SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height)
  89. {
  90. try
  91. {
  92. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  93. //在位图中呈现UI元素
  94. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d,
  95. System.Windows.Media.PixelFormats.Pbgra32);
  96. bmp.Render(ui);
  97. BitmapEncoder encoder = new PngBitmapEncoder();
  98. encoder.Frames.Add(BitmapFrame.Create(bmp));
  99. encoder.Save(fs);
  100. fs.Close();
  101. }
  102. catch (Exception ex)
  103. {
  104. LogHelper.WriteErrLog("【UI生成图片】(SaveUIToImage)" + ex.Message, ex);
  105. //Console.WriteLine(ex.Message);
  106. }
  107. }
  108. #endregion
  109. /// <summary>
  110. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  111. /// </summary>
  112. /// <param name="path">图片位置</param>
  113. /// <returns></returns>
  114. public static BitmapImage ReadBitmapImageFile(string path)
  115. {
  116. BitmapImage bitmap = new BitmapImage();
  117. try
  118. {
  119. using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path)))
  120. {
  121. bitmap = new BitmapImage
  122. {
  123. DecodePixelHeight = 100
  124. };
  125. bitmap.BeginInit();
  126. bitmap.CacheOption = BitmapCacheOption.OnLoad;//设置缓存模式
  127. bitmap.StreamSource = ms;//通过StreamSource加载图片
  128. bitmap.EndInit();
  129. bitmap.Freeze();
  130. }
  131. return bitmap;
  132. }
  133. catch (Exception)
  134. {
  135. return null;
  136. }
  137. }
  138. #region 获取RGB
  139. private static Bitmap _Bitmap = null;
  140. private static StringBuilder sb = new StringBuilder();
  141. public static string GetRGB(int x, int y)
  142. {
  143. sb = new StringBuilder();
  144. try
  145. {
  146. System.Drawing.Color color = _Bitmap.GetPixel(x, y);
  147. sb.Append("RGB:(");
  148. sb.Append(color.R.ToString());
  149. sb.Append(",");
  150. sb.Append(color.G.ToString());
  151. sb.Append(",");
  152. sb.Append(color.B.ToString());
  153. sb.Append(")");
  154. }
  155. catch (Exception ex)
  156. {
  157. LogHelper.WriteErrLog("ImageHelper(GetRGB)" + ex.Message, ex);
  158. }
  159. return sb.ToString();
  160. }
  161. #endregion 获取RGB
  162. #region 截图统一方法
  163. /// <summary>
  164. /// 截图通用方法 创建人:赵耀 创建时间:2020年8月11日
  165. /// </summary>
  166. /// <param name="ScreenSize">截图的区域,设置new Rectangle(0, 0, 0, 0)为截全屏</param>
  167. /// <param name="ImageSavePath">图片存储路径,为空或null则保存到临时文件夹</param>
  168. /// <param name="IsRetImg">是否返回图片</param>
  169. /// <param name="bitmapimg">图片</param>
  170. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  171. /// <returns></returns>
  172. public static bool GetScreenshot(Rectangle ScreenSize, string ImageSavePath, bool IsRetImg, out BitmapImage bitmapimg, long level = -1)
  173. {
  174. bitmapimg = null;
  175. try
  176. {
  177. System.Drawing.Size bounds = PrimaryScreen.DESKTOP;
  178. if (string.IsNullOrEmpty(ImageSavePath))
  179. {
  180. ImageSavePath = GetTempImagePath();//如果为空则指定临时存储路径
  181. }
  182. double scaleWidth = (bounds.Width * 1.0) / SystemParameters.PrimaryScreenWidth;
  183. double scaleHeight = (bounds.Height * 1.0) / SystemParameters.PrimaryScreenHeight;
  184. int width = bounds.Width;
  185. int height = bounds.Height;
  186. if (ScreenSize.Size != new System.Drawing.Size(0, 0))
  187. {
  188. width = (int)(ScreenSize.Size.Width * scaleWidth);
  189. height = (int)(ScreenSize.Size.Height * scaleHeight);
  190. }
  191. int l = (int)(ScreenSize.X * scaleWidth);
  192. int t = (int)(ScreenSize.Y * scaleHeight);
  193. if (_Bitmap != null)
  194. {
  195. _Bitmap.Dispose();
  196. }
  197. _Bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  198. using (Graphics g = Graphics.FromImage(_Bitmap))
  199. {
  200. g.CopyFromScreen(l, t, 0, 0, _Bitmap.Size, CopyPixelOperation.SourceCopy);
  201. Compress(_Bitmap, ImageSavePath, level);
  202. }
  203. if (IsRetImg)
  204. {
  205. Uri uri = new Uri(ImageSavePath, UriKind.Absolute);
  206. bitmapimg = new BitmapImage(uri);
  207. }
  208. GC.Collect();
  209. return true;
  210. }
  211. catch (Exception ex)
  212. {
  213. LogHelper.WriteErrLog("【截图】(GetBitmapSource)截图失败," + ex.Message, ex);
  214. return false;
  215. }
  216. }
  217. /// <summary>
  218. /// 获取临时图片保存位置
  219. /// </summary>
  220. /// <returns></returns>
  221. public static string GetTempImagePath()
  222. {
  223. TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  224. string TempPath = FileToolsCommon.GetFileAbsolutePath("/temp/Screenshot/");
  225. FileToolsCommon.CreateDirectory(TempPath);
  226. TempPath += Convert.ToInt64(ts.TotalMilliseconds).ToString() + ".jpg";
  227. return TempPath;
  228. }
  229. #endregion 截图统一方法
  230. #region 图片压缩
  231. /// <summary>
  232. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  233. /// </summary>
  234. /// <param name="srcBitMap">传入的Bitmap对象</param>
  235. /// <param name="destFile">压缩后的图片保存路径</param>
  236. /// <param name="level">压缩等级,-1为config配置的值,0到100,0 最差质量,100 最佳</param>
  237. public static void Compress(Bitmap srcBitMap, string destFile, long level)
  238. {
  239. if (level <= -1)
  240. {
  241. int ImageCompressionLevel = int.Parse(FileToolsCommon.GetConfigValue("ImageCompressionLevel"));
  242. level = ImageCompressionLevel;
  243. }
  244. Stream s = new FileStream(destFile, FileMode.Create);
  245. Compress(srcBitMap, s, level);
  246. s.Close();
  247. }
  248. /// <summary>
  249. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  250. /// </summary>
  251. /// <param name="srcBitmap">传入的Bitmap对象</param>
  252. /// <param name="destStream">压缩后的Stream对象</param>
  253. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  254. public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
  255. {
  256. ImageCodecInfo myImageCodecInfo;
  257. System.Drawing.Imaging.Encoder myEncoder;
  258. EncoderParameter myEncoderParameter;
  259. EncoderParameters myEncoderParameters;
  260. //获取表示jpeg编解码器的imagecodecinfo对象
  261. myImageCodecInfo = GetEncoderInfo("image/jpeg");
  262. myEncoder = System.Drawing.Imaging.Encoder.Quality;
  263. myEncoderParameters = new EncoderParameters(1);
  264. myEncoderParameter = new EncoderParameter(myEncoder, level);
  265. myEncoderParameters.Param[0] = myEncoderParameter;
  266. srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
  267. }
  268. /// <summary>
  269. /// 获取解码器 创建人:赵耀 创建时间2020年8月11日
  270. /// </summary>
  271. /// <param name="mimeType"></param>
  272. /// <returns></returns>
  273. private static ImageCodecInfo GetEncoderInfo(string mimeType)
  274. {
  275. int j;
  276. ImageCodecInfo[] encoders;
  277. encoders = ImageCodecInfo.GetImageEncoders();
  278. for (j = 0; j < encoders.Length; ++j)
  279. {
  280. if (encoders[j].MimeType == mimeType)
  281. {
  282. return encoders[j];
  283. }
  284. }
  285. return null;
  286. }
  287. /// <summary>
  288. /// 压缩图片 -测试方法 待完善 暂无用
  289. /// </summary>
  290. /// <param name="_bitmap">原图片</param>
  291. /// <param name="dFile">压缩后保存图片地址</param>
  292. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  293. /// <param name="size">压缩后图片的最大大小</param>
  294. /// <param name="sfsc">是否是第一次调用</param>
  295. /// <returns></returns>
  296. public static bool CompressImage(Bitmap _bitmap, string dFile, int flag = 90, int size = 300)
  297. {
  298. ////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  299. //FileInfo firstFileInfo = new FileInfo(sFile);
  300. //if (sfsc == true && firstFileInfo.Length < size * 1024)
  301. //{
  302. // firstFileInfo.CopyTo(dFile);
  303. // return true;
  304. //}
  305. //Image iSource = Image.FromFile(sFile);
  306. Image iSource = _bitmap;
  307. ImageFormat tFormat = iSource.RawFormat;
  308. int dHeight = iSource.Height / 2;
  309. int dWidth = iSource.Width / 2;
  310. int sW, sH;
  311. //按比例缩放
  312. System.Drawing.Size tem_size = new System.Drawing.Size(iSource.Width, iSource.Height);
  313. if (tem_size.Width > dHeight || tem_size.Width > dWidth)
  314. {
  315. if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
  316. {
  317. sW = dWidth;
  318. sH = (dWidth * tem_size.Height) / tem_size.Width;
  319. }
  320. else
  321. {
  322. sH = dHeight;
  323. sW = (tem_size.Width * dHeight) / tem_size.Height;
  324. }
  325. }
  326. else
  327. {
  328. sW = tem_size.Width;
  329. sH = tem_size.Height;
  330. }
  331. Bitmap ob = new Bitmap(dWidth, dHeight);
  332. Graphics g = Graphics.FromImage(ob);
  333. g.Clear(System.Drawing.Color.WhiteSmoke);
  334. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  335. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  336. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  337. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  338. g.Dispose();
  339. //以下代码为保存图片时,设置压缩质量
  340. EncoderParameters ep = new EncoderParameters();
  341. long[] qy = new long[1];
  342. qy[0] = flag;//设置压缩的比例1-100
  343. EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
  344. ep.Param[0] = eParam;
  345. try
  346. {
  347. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
  348. ImageCodecInfo jpegICIinfo = null;
  349. for (int x = 0; x < arrayICI.Length; x++)
  350. {
  351. if (arrayICI[x].FormatDescription.Equals("JPEG"))
  352. {
  353. jpegICIinfo = arrayICI[x];
  354. break;
  355. }
  356. }
  357. if (jpegICIinfo != null)
  358. {
  359. if (flag > 0)
  360. {
  361. ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
  362. FileInfo fi = new FileInfo(dFile);
  363. if (fi.Length > 1024 * size)
  364. {
  365. flag -= 10;
  366. CompressImage(_bitmap, dFile, flag, size);
  367. }
  368. }
  369. //ob.Save(dFile, jpegICIinfo, ep);
  370. //FileInfo fi = new FileInfo(dFile);
  371. //bool IsAgain = false;
  372. //if (fi.Length > 1024 * size)
  373. //{
  374. // fi.CopyTo(dFile + fi.Length);
  375. // fi.Delete();
  376. // Bitmap newbitmap = ReadImageFile(dFile + fi.Length);
  377. // CompressImage(newbitmap, dFile, flag, size);
  378. // FileToolsCommon.DeleteFile(dFile + fi.Length);
  379. //}
  380. }
  381. else
  382. {
  383. ob.Save(dFile, tFormat);
  384. }
  385. return true;
  386. }
  387. catch
  388. {
  389. return false;
  390. }
  391. finally
  392. {
  393. iSource.Dispose();
  394. ob.Dispose();
  395. }
  396. }
  397. #endregion 图片压缩
  398. #region 截屏指定UI控件
  399. /// <summary>
  400. /// 保存图片
  401. /// </summary>
  402. /// <param name="ui">需要截图的UI控件</param>
  403. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  404. /// <param name="width">图片宽</param>
  405. /// <param name="height">图片高</param>
  406. /// <param name="ImgWidth">转换后高</param>
  407. /// <param name="ImgHeight">转换后高</param>
  408. public static void SaveUI(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
  409. {
  410. try
  411. {
  412. //在位图中呈现UI元素
  413. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  414. bmp.Render(ui);
  415. //定义切割矩形
  416. var cut = new Int32Rect(0, 0, width, height);
  417. //计算Stride
  418. var stride = bmp.Format.BitsPerPixel * cut.Width / 8;
  419. //声明字节数组
  420. byte[] data = new byte[cut.Height * stride];
  421. //调用CopyPixels
  422. bmp.CopyPixels(cut, data, stride, 0);
  423. new Thread(new ThreadStart(new Action(() =>
  424. {
  425. BitmapSource bitmapSource = BitmapSource.Create(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Bgr32, null, data, stride);
  426. BitmapEncoder encoder = new PngBitmapEncoder();
  427. encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
  428. if (ImgWidth > 0)
  429. {
  430. Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
  431. try
  432. {
  433. //MemoryStream memoryStream = new MemoryStream(data);
  434. //Bitmap bit = (Bitmap)Image.FromStream(memoryStream);
  435. MemoryStream memoryStream = new MemoryStream();
  436. encoder.Save(memoryStream);
  437. Bitmap bit = new Bitmap(memoryStream, true);
  438. if (ImgWidth - 2 < bit.Width)
  439. {
  440. try
  441. {
  442. Graphics g = Graphics.FromImage(Img);
  443. g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
  444. g.Dispose();
  445. }
  446. catch
  447. {
  448. Img = bit;
  449. }
  450. }
  451. else
  452. {
  453. Img = bit;
  454. }
  455. Img.Save(filePathName);
  456. memoryStream.Dispose();
  457. Img.Dispose();
  458. bit.Dispose();
  459. }
  460. catch (Exception)
  461. {
  462. using (var stream = new FileStream(filePathName, FileMode.Create))
  463. {
  464. encoder.Save(stream);
  465. }
  466. }
  467. }
  468. else
  469. {
  470. using (var stream = new FileStream(filePathName, FileMode.Create))
  471. {
  472. encoder.Save(stream);
  473. }
  474. }
  475. }))).Start();
  476. }
  477. catch (Exception)
  478. {
  479. }
  480. }
  481. /// <summary>
  482. /// 保存图片
  483. /// </summary>
  484. /// <param name="ui">需要截图的UI控件</param>
  485. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  486. /// <param name="width">窗口宽</param>
  487. /// <param name="height">窗口高</param>
  488. /// <param name="ImgWidth">图片高</param>
  489. /// <param name="ImgHeight">图片高</param>
  490. public static void SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
  491. {
  492. try
  493. {
  494. //在位图中呈现UI元素
  495. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  496. bmp.Render(ui);
  497. BitmapEncoder encoder = new PngBitmapEncoder();
  498. encoder.Frames.Add(BitmapFrame.Create(bmp));
  499. if (ImgWidth > 0)
  500. {
  501. Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
  502. try
  503. {
  504. MemoryStream memoryStream = new MemoryStream();
  505. encoder.Save(memoryStream);
  506. new Thread(new ThreadStart(new Action(() =>
  507. {
  508. //System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);
  509. Bitmap bit = new Bitmap(memoryStream);
  510. if (ImgWidth - 2 < bit.Width)
  511. {
  512. try
  513. {
  514. Graphics g = Graphics.FromImage(Img);
  515. //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  516. g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
  517. g.Dispose();
  518. }
  519. catch
  520. {
  521. Img = bit;
  522. }
  523. }
  524. else
  525. {
  526. Img = bit;
  527. }
  528. Img.Save(filePathName);
  529. //Bitmap bitmap = CutImageWhitePart(Img);
  530. //FileToolsCommon.DeleteFile(filePathName);
  531. //bitmap.Save(filePathName);
  532. //bitmap.Dispose();
  533. memoryStream.Dispose();
  534. Img.Dispose();
  535. bit.Dispose();
  536. }))).Start();
  537. }
  538. catch (Exception)
  539. {
  540. }
  541. }
  542. else
  543. {
  544. //SaveImageModel sim = new SaveImageModel();
  545. //sim.encoder = new PngBitmapEncoder();
  546. //sim.encoder = new PngBitmapEncoder();
  547. //BitmapFrame test= encoder.Frames[0];
  548. //sim.encoder.Frames.Add(BitmapFrame.Create(test));
  549. ////sim.encoder.Frames[0].CopyTo(encoder.Frames[0]);
  550. ////sim.encoder.CopyTo(encoder);
  551. ////encoder.CopyTo(sim.encoder);
  552. //sim.FilePath = filePathName;
  553. ////sim.bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  554. ////bmp.CopyTo(sim.bmp);
  555. //Thread t1 = new Thread(SaveImage);
  556. //t1.Start(sim);
  557. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  558. encoder.Save(fs);
  559. fs.Close();
  560. }
  561. }
  562. catch (Exception ex)
  563. {
  564. LogHelper.WriteErrLog("【UI生成图片】(SaveUIToImage)" + ex.Message, ex);
  565. //Console.WriteLine(ex.Message);
  566. }
  567. }
  568. public static void SaveUI1(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
  569. {
  570. try
  571. {
  572. //在位图中呈现UI元素
  573. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  574. bmp.Render(ui);
  575. //BitmapEncoder encoder = new PngBitmapEncoder();
  576. //encoder.Frames.Add(BitmapFrame.Create(bmp));
  577. //BitmapSource bitmapSource= bmp.Clone();
  578. //定义切割矩形
  579. var cut = new Int32Rect(0, 0, width, height);
  580. //计算Stride
  581. var stride = bmp.Format.BitsPerPixel * cut.Width / 8;
  582. //声明字节数组
  583. byte[] data = new byte[cut.Height * stride];
  584. //调用CopyPixels
  585. bmp.CopyPixels(cut, data, stride, 0);
  586. new Thread(new ThreadStart(new Action(() =>
  587. {
  588. BitmapSource bitmapSource = BitmapSource.Create(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Bgr32, null, data, stride);
  589. BitmapEncoder encoder = new PngBitmapEncoder();
  590. encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
  591. using (var stream = new FileStream(filePathName, FileMode.Create))
  592. {
  593. encoder.Save(stream);
  594. }
  595. }))).Start();
  596. //SaveModel saveModel = new SaveModel();
  597. //saveModel.ImgWidth = ImgWidth;
  598. //saveModel.ImgHeight = ImgHeight;
  599. //saveModel.filePathName = filePathName;
  600. //saveModel.bmp = bmp;
  601. //saveModel.encoder =new PngBitmapEncoder();
  602. //foreach (BitmapFrame eitem in encoder.Frames)
  603. //{
  604. // saveModel.encoder = new PngBitmapEncoder();
  605. // saveModel.encoder.Frames.Add( eitem );
  606. //}
  607. //Thread myThread = new Thread(SaveImage);
  608. //myThread.Start(saveModel);
  609. }
  610. catch (Exception)
  611. {
  612. }
  613. }
  614. public static void SaveImage(object model)
  615. {
  616. try
  617. {
  618. SaveModel saveModel = (SaveModel)model;
  619. int ImgWidth = saveModel.ImgWidth;
  620. int ImgHeight = saveModel.ImgHeight;
  621. //BitmapEncoder encoder = saveModel.encoder;
  622. RenderTargetBitmap bmp = saveModel.bmp;
  623. BitmapEncoder encoder = new PngBitmapEncoder();
  624. encoder.Frames.Add(BitmapFrame.Create(bmp));
  625. string filePathName = saveModel.filePathName;
  626. if (ImgWidth > 0)
  627. {
  628. Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
  629. try
  630. {
  631. MemoryStream memoryStream = new MemoryStream();
  632. encoder.Save(memoryStream);
  633. new Thread(new ThreadStart(new Action(() =>
  634. {
  635. //System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);
  636. Bitmap bit = new Bitmap(memoryStream);
  637. if (ImgWidth - 2 < bit.Width)
  638. {
  639. try
  640. {
  641. Graphics g = Graphics.FromImage(Img);
  642. //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  643. g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
  644. g.Dispose();
  645. }
  646. catch
  647. {
  648. Img = bit;
  649. }
  650. }
  651. else
  652. {
  653. Img = bit;
  654. }
  655. Img.Save(filePathName);
  656. //Bitmap bitmap = CutImageWhitePart(Img);
  657. //FileToolsCommon.DeleteFile(filePathName);
  658. //bitmap.Save(filePathName);
  659. //bitmap.Dispose();
  660. memoryStream.Dispose();
  661. Img.Dispose();
  662. bit.Dispose();
  663. }))).Start();
  664. }
  665. catch (Exception)
  666. {
  667. }
  668. }
  669. else
  670. {
  671. //SaveImageModel sim = new SaveImageModel();
  672. //sim.encoder = new PngBitmapEncoder();
  673. //sim.encoder = new PngBitmapEncoder();
  674. //BitmapFrame test= encoder.Frames[0];
  675. //sim.encoder.Frames.Add(BitmapFrame.Create(test));
  676. ////sim.encoder.Frames[0].CopyTo(encoder.Frames[0]);
  677. ////sim.encoder.CopyTo(encoder);
  678. ////encoder.CopyTo(sim.encoder);
  679. //sim.FilePath = filePathName;
  680. ////sim.bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  681. ////bmp.CopyTo(sim.bmp);
  682. //Thread t1 = new Thread(SaveImage);
  683. //t1.Start(sim);
  684. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  685. encoder.Save(fs);
  686. fs.Close();
  687. }
  688. }
  689. catch (Exception)
  690. {
  691. }
  692. }
  693. /// <summary>
  694. /// 截图转换成bitmap
  695. /// </summary>
  696. /// <param name="element"></param>
  697. /// <param name="width">默认控件宽度</param>
  698. /// <param name="height">默认控件高度</param>
  699. /// <param name="x">默认0</param>
  700. /// <param name="y">默认0</param>
  701. /// <returns></returns>
  702. public static Bitmap ToBitmap(FrameworkElement element, string filePathName, int width = 0, int height = 0, int x = 0, int y = 0)
  703. {
  704. if (width == 0) width = (int)element.ActualWidth;
  705. if (height == 0) height = (int)element.ActualHeight;
  706. var rtb = new RenderTargetBitmap(width, height, x, y, System.Windows.Media.PixelFormats.Default);
  707. rtb.Render(element);
  708. var bit = BitmapSourceToBitmap(rtb);
  709. //测试代码
  710. DirectoryInfo d = new DirectoryInfo(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Cache"));
  711. if (!d.Exists) d.Create();
  712. bit.Save(System.IO.Path.Combine(d.FullName, "控件截图.png"));
  713. return bit;
  714. }
  715. /// <summary>
  716. /// BitmapSource转Bitmap
  717. /// </summary>
  718. /// <param name="source"></param>
  719. /// <returns></returns>
  720. public static Bitmap BitmapSourceToBitmap(BitmapSource source)
  721. {
  722. return BitmapSourceToBitmap(source, source.PixelWidth, source.PixelHeight);
  723. }
  724. /// <summary>
  725. /// Convert BitmapSource to Bitmap
  726. /// </summary>
  727. /// <param name="source"></param>
  728. /// <returns></returns>
  729. public static Bitmap BitmapSourceToBitmap(BitmapSource source, int width, int height)
  730. {
  731. Bitmap bmp = null;
  732. try
  733. {
  734. System.Drawing.Imaging.PixelFormat format = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
  735. /*set the translate type according to the in param(source)*/
  736. switch (source.Format.ToString())
  737. {
  738. case "Rgb24":
  739. case "Bgr24": format = System.Drawing.Imaging.PixelFormat.Format24bppRgb; break;
  740. case "Bgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; break;
  741. case "Bgr32": format = System.Drawing.Imaging.PixelFormat.Format32bppRgb; break;
  742. case "Pbgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppArgb; break;
  743. }
  744. bmp = new Bitmap(width, height, format);
  745. BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
  746. ImageLockMode.WriteOnly,
  747. format);
  748. source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
  749. bmp.UnlockBits(data);
  750. }
  751. catch
  752. {
  753. if (bmp != null)
  754. {
  755. bmp.Dispose();
  756. bmp = null;
  757. }
  758. }
  759. return bmp;
  760. }
  761. private static void SaveImage1(object obj)
  762. {
  763. SaveImageModel sim = (SaveImageModel)obj;
  764. //RenderTargetBitmap bmp = sim.bmp;
  765. //BitmapEncoder encoder = new PngBitmapEncoder();
  766. //encoder.Frames.Add(BitmapFrame.Create(bmp));
  767. BitmapEncoder encoder = sim.encoder;
  768. string filePathName = sim.FilePath;
  769. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  770. encoder.Save(fs);
  771. fs.Close();
  772. }
  773. #endregion
  774. #region 去掉白边
  775. /// <summary>
  776. /// 裁剪图片(去掉白边)
  777. /// </summary>
  778. /// <param name="FilePath"></param>
  779. public static Bitmap CutImageWhitePart(Bitmap bmp)
  780. {
  781. //Bitmap bmp = new Bitmap(FilePath);
  782. //上左右下
  783. int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
  784. //寻找最上面的标线,从左(0)到右,从上(0)到下
  785. for (int i = 0; i < bmp.Height; i++)//行
  786. {
  787. bool find = false;
  788. for (int j = 0; j < bmp.Width; j++)//列
  789. {
  790. System.Drawing.Color c = bmp.GetPixel(j, i);
  791. if (!IsWhite(c))
  792. {
  793. top = i;
  794. find = true;
  795. break;
  796. }
  797. }
  798. if (find)
  799. {
  800. break;
  801. }
  802. }
  803. //寻找最左边的标线,从上(top位)到下,从左到右
  804. for (int i = 0; i < bmp.Width; i++)//列
  805. {
  806. bool find = false;
  807. for (int j = top; j < bmp.Height; j++)//行
  808. {
  809. System.Drawing.Color c = bmp.GetPixel(i, j);
  810. if (!IsWhite(c))
  811. {
  812. left = i;
  813. find = true;
  814. break;
  815. }
  816. }
  817. if (find)
  818. {
  819. break;
  820. }
  821. }
  822. //寻找最下边标线,从下到上,从左到右
  823. for (int i = bmp.Height - 1; i >= 0; i--)//行
  824. {
  825. bool find = false;
  826. for (int j = left; j < bmp.Width; j++)//列
  827. {
  828. System.Drawing.Color c = bmp.GetPixel(j, i);
  829. if (!IsWhite(c))
  830. {
  831. bottom = i;
  832. find = true;
  833. break;
  834. }
  835. }
  836. if (find)
  837. {
  838. break;
  839. }
  840. }
  841. //寻找最右边的标线,从上到下,从右往左
  842. for (int i = bmp.Width - 1; i >= 0; i--)//列
  843. {
  844. bool find = false;
  845. for (int j = 0; j <= bottom; j++)//行
  846. {
  847. System.Drawing.Color c = bmp.GetPixel(i, j);
  848. if (!IsWhite(c))
  849. {
  850. right = i;
  851. find = true;
  852. break;
  853. }
  854. }
  855. if (find)
  856. {
  857. break;
  858. }
  859. }
  860. if (right - left <= 0)//zxyceshi
  861. {
  862. //克隆位图对象的一部分。
  863. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, 1, bottom - top);
  864. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  865. bmp.Dispose();
  866. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  867. return cloneBitmap;
  868. }
  869. else
  870. {
  871. //克隆位图对象的一部分。
  872. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, right - left, bottom - top);
  873. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  874. bmp.Dispose();
  875. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  876. return cloneBitmap;
  877. }
  878. }
  879. /// <summary>
  880. /// 判断是否白色和纯透明色(10点的容差)
  881. /// </summary>
  882. public static bool IsWhite(System.Drawing.Color c)
  883. {
  884. //纯透明也是白色,RGB都为255为纯白
  885. if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
  886. {
  887. return true;
  888. }
  889. return false;
  890. }
  891. #endregion
  892. }
  893. public class SaveImageModel
  894. {
  895. public string FilePath { get; set; }
  896. public BitmapEncoder encoder { get; set; }
  897. //public RenderTargetBitmap bmp { get; set; }
  898. }
  899. public class SaveModel
  900. {
  901. public int ImgWidth { get; set; }
  902. public int ImgHeight { get; set; }
  903. public BitmapEncoder encoder { get; set; }
  904. public string filePathName { get; set; }
  905. public RenderTargetBitmap bmp { get; set; }
  906. }
  907. }