星火微课系统客户端
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ImageHelper.cs 37KB

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