星火微课系统客户端
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
4 роки тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
  380. {
  381. //SaveUI(ui, filePathName, width, height, ImgWidth, ImgHeight);
  382. //return;
  383. try
  384. {
  385. //在位图中呈现UI元素
  386. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  387. bmp.Render(ui);
  388. BitmapEncoder encoder = new PngBitmapEncoder();
  389. encoder.Frames.Add(BitmapFrame.Create(bmp));
  390. if (ImgWidth > 0)
  391. {
  392. Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
  393. try
  394. {
  395. MemoryStream memoryStream = new MemoryStream();
  396. encoder.Save(memoryStream);
  397. new Thread(new ThreadStart(new Action(() =>
  398. {
  399. //System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);
  400. Bitmap bit = new Bitmap(memoryStream);
  401. if (ImgWidth - 2 < bit.Width)
  402. {
  403. try
  404. {
  405. Graphics g = Graphics.FromImage(Img);
  406. //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  407. g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
  408. g.Dispose();
  409. }
  410. catch
  411. {
  412. Img = bit;
  413. }
  414. }
  415. else
  416. {
  417. Img = bit;
  418. }
  419. Img.Save(filePathName);
  420. //Bitmap bitmap = CutImageWhitePart(Img);
  421. //FileToolsCommon.DeleteFile(filePathName);
  422. //bitmap.Save(filePathName);
  423. //bitmap.Dispose();
  424. memoryStream.Dispose();
  425. Img.Dispose();
  426. bit.Dispose();
  427. }))).Start();
  428. }
  429. catch (Exception)
  430. {
  431. }
  432. }
  433. else
  434. {
  435. //SaveImageModel sim = new SaveImageModel();
  436. //sim.encoder = new PngBitmapEncoder();
  437. //sim.encoder = new PngBitmapEncoder();
  438. //BitmapFrame test= encoder.Frames[0];
  439. //sim.encoder.Frames.Add(BitmapFrame.Create(test));
  440. ////sim.encoder.Frames[0].CopyTo(encoder.Frames[0]);
  441. ////sim.encoder.CopyTo(encoder);
  442. ////encoder.CopyTo(sim.encoder);
  443. //sim.FilePath = filePathName;
  444. ////sim.bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  445. ////bmp.CopyTo(sim.bmp);
  446. //Thread t1 = new Thread(SaveImage);
  447. //t1.Start(sim);
  448. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  449. encoder.Save(fs);
  450. fs.Close();
  451. }
  452. }
  453. catch (Exception ex)
  454. {
  455. LogHelper.WriteErrLog("【UI生成图片】(SaveUIToImage)" + ex.Message, ex);
  456. //Console.WriteLine(ex.Message);
  457. }
  458. }
  459. public static void SaveUI(FrameworkElement ui, string filePathName, int width, int height, int ImgWidth, int ImgHeight)
  460. {
  461. try
  462. {
  463. //在位图中呈现UI元素
  464. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  465. bmp.Render(ui);
  466. BitmapEncoder encoder = new PngBitmapEncoder();
  467. encoder.Frames.Add(BitmapFrame.Create(bmp));
  468. SaveModel saveModel = new SaveModel();
  469. saveModel.ImgWidth = ImgWidth;
  470. saveModel.ImgHeight = ImgHeight;
  471. saveModel.filePathName = filePathName;
  472. saveModel.bmp = bmp;
  473. //定义切割矩形
  474. var cut = new Int32Rect(0, 0, width, height);
  475. //计算Stride
  476. var stride = bmp.Format.BitsPerPixel * cut.Width / 8;
  477. //声明字节数组
  478. byte[] data = new byte[cut.Height * stride];
  479. //调用CopyPixels
  480. bmp.CopyPixels(cut, data, stride, 0);
  481. //saveModel.encoder =new PngBitmapEncoder();
  482. //foreach (BitmapFrame eitem in encoder.Frames)
  483. //{
  484. // saveModel.encoder = new PngBitmapEncoder();
  485. // saveModel.encoder.Frames.Add( eitem );
  486. //}
  487. Thread myThread = new Thread(SaveImage);
  488. myThread.Start(saveModel);
  489. }
  490. catch (Exception ex)
  491. {
  492. }
  493. }
  494. public static void SaveImage(object model)
  495. {
  496. try
  497. {
  498. SaveModel saveModel = (SaveModel)model;
  499. int ImgWidth = saveModel.ImgWidth;
  500. int ImgHeight = saveModel.ImgHeight;
  501. //BitmapEncoder encoder = saveModel.encoder;
  502. RenderTargetBitmap bmp = saveModel.bmp;
  503. BitmapEncoder encoder = new PngBitmapEncoder();
  504. encoder.Frames.Add(BitmapFrame.Create(bmp));
  505. string filePathName = saveModel.filePathName;
  506. if (ImgWidth > 0)
  507. {
  508. Bitmap Img = new Bitmap(ImgWidth, ImgHeight);
  509. try
  510. {
  511. MemoryStream memoryStream = new MemoryStream();
  512. encoder.Save(memoryStream);
  513. new Thread(new ThreadStart(new Action(() =>
  514. {
  515. //System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);
  516. Bitmap bit = new Bitmap(memoryStream);
  517. if (ImgWidth - 2 < bit.Width)
  518. {
  519. try
  520. {
  521. Graphics g = Graphics.FromImage(Img);
  522. //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  523. g.DrawImage(bit, new Rectangle(0, 0, ImgWidth, ImgHeight), new Rectangle(0, 0, bit.Width, bit.Height), GraphicsUnit.Pixel);
  524. g.Dispose();
  525. }
  526. catch
  527. {
  528. Img = bit;
  529. }
  530. }
  531. else
  532. {
  533. Img = bit;
  534. }
  535. Img.Save(filePathName);
  536. //Bitmap bitmap = CutImageWhitePart(Img);
  537. //FileToolsCommon.DeleteFile(filePathName);
  538. //bitmap.Save(filePathName);
  539. //bitmap.Dispose();
  540. memoryStream.Dispose();
  541. Img.Dispose();
  542. bit.Dispose();
  543. }))).Start();
  544. }
  545. catch (Exception ex)
  546. {
  547. }
  548. }
  549. else
  550. {
  551. //SaveImageModel sim = new SaveImageModel();
  552. //sim.encoder = new PngBitmapEncoder();
  553. //sim.encoder = new PngBitmapEncoder();
  554. //BitmapFrame test= encoder.Frames[0];
  555. //sim.encoder.Frames.Add(BitmapFrame.Create(test));
  556. ////sim.encoder.Frames[0].CopyTo(encoder.Frames[0]);
  557. ////sim.encoder.CopyTo(encoder);
  558. ////encoder.CopyTo(sim.encoder);
  559. //sim.FilePath = filePathName;
  560. ////sim.bmp = new RenderTargetBitmap(width, height, PrimaryScreen.DpiX, PrimaryScreen.DpiY, PixelFormats.Pbgra32);
  561. ////bmp.CopyTo(sim.bmp);
  562. //Thread t1 = new Thread(SaveImage);
  563. //t1.Start(sim);
  564. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  565. encoder.Save(fs);
  566. fs.Close();
  567. }
  568. }
  569. catch (Exception ex)
  570. {
  571. }
  572. }
  573. /// <summary>
  574. /// 截图转换成bitmap
  575. /// </summary>
  576. /// <param name="element"></param>
  577. /// <param name="width">默认控件宽度</param>
  578. /// <param name="height">默认控件高度</param>
  579. /// <param name="x">默认0</param>
  580. /// <param name="y">默认0</param>
  581. /// <returns></returns>
  582. public static Bitmap ToBitmap(FrameworkElement element, string filePathName, int width = 0, int height = 0, int x = 0, int y = 0)
  583. {
  584. if (width == 0) width = (int)element.ActualWidth;
  585. if (height == 0) height = (int)element.ActualHeight;
  586. var rtb = new RenderTargetBitmap(width, height, x, y, System.Windows.Media.PixelFormats.Default);
  587. rtb.Render(element);
  588. var bit = BitmapSourceToBitmap(rtb);
  589. //测试代码
  590. DirectoryInfo d = new DirectoryInfo(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Cache"));
  591. if (!d.Exists) d.Create();
  592. bit.Save(System.IO.Path.Combine(d.FullName, "控件截图.png"));
  593. return bit;
  594. }
  595. /// <summary>
  596. /// BitmapSource转Bitmap
  597. /// </summary>
  598. /// <param name="source"></param>
  599. /// <returns></returns>
  600. public static Bitmap BitmapSourceToBitmap(BitmapSource source)
  601. {
  602. return BitmapSourceToBitmap(source, source.PixelWidth, source.PixelHeight);
  603. }
  604. /// <summary>
  605. /// Convert BitmapSource to Bitmap
  606. /// </summary>
  607. /// <param name="source"></param>
  608. /// <returns></returns>
  609. public static Bitmap BitmapSourceToBitmap(BitmapSource source, int width, int height)
  610. {
  611. Bitmap bmp = null;
  612. try
  613. {
  614. System.Drawing.Imaging.PixelFormat format = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
  615. /*set the translate type according to the in param(source)*/
  616. switch (source.Format.ToString())
  617. {
  618. case "Rgb24":
  619. case "Bgr24": format = System.Drawing.Imaging.PixelFormat.Format24bppRgb; break;
  620. case "Bgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; break;
  621. case "Bgr32": format = System.Drawing.Imaging.PixelFormat.Format32bppRgb; break;
  622. case "Pbgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppArgb; break;
  623. }
  624. bmp = new Bitmap(width, height, format);
  625. BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
  626. ImageLockMode.WriteOnly,
  627. format);
  628. source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
  629. bmp.UnlockBits(data);
  630. }
  631. catch
  632. {
  633. if (bmp != null)
  634. {
  635. bmp.Dispose();
  636. bmp = null;
  637. }
  638. }
  639. return bmp;
  640. }
  641. private static void SaveImage1(object obj)
  642. {
  643. SaveImageModel sim = (SaveImageModel)obj;
  644. //RenderTargetBitmap bmp = sim.bmp;
  645. //BitmapEncoder encoder = new PngBitmapEncoder();
  646. //encoder.Frames.Add(BitmapFrame.Create(bmp));
  647. BitmapEncoder encoder = sim.encoder;
  648. string filePathName = sim.FilePath;
  649. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  650. encoder.Save(fs);
  651. fs.Close();
  652. }
  653. #endregion
  654. #region 去掉白边
  655. /// <summary>
  656. /// 裁剪图片(去掉白边)
  657. /// </summary>
  658. /// <param name="FilePath"></param>
  659. public static Bitmap CutImageWhitePart(Bitmap bmp)
  660. {
  661. //Bitmap bmp = new Bitmap(FilePath);
  662. //上左右下
  663. int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
  664. //寻找最上面的标线,从左(0)到右,从上(0)到下
  665. for (int i = 0; i < bmp.Height; i++)//行
  666. {
  667. bool find = false;
  668. for (int j = 0; j < bmp.Width; j++)//列
  669. {
  670. System.Drawing.Color c = bmp.GetPixel(j, i);
  671. if (!IsWhite(c))
  672. {
  673. top = i;
  674. find = true;
  675. break;
  676. }
  677. }
  678. if (find)
  679. {
  680. break;
  681. }
  682. }
  683. //寻找最左边的标线,从上(top位)到下,从左到右
  684. for (int i = 0; i < bmp.Width; i++)//列
  685. {
  686. bool find = false;
  687. for (int j = top; j < bmp.Height; j++)//行
  688. {
  689. System.Drawing.Color c = bmp.GetPixel(i, j);
  690. if (!IsWhite(c))
  691. {
  692. left = i;
  693. find = true;
  694. break;
  695. }
  696. }
  697. if (find)
  698. {
  699. break;
  700. }
  701. }
  702. //寻找最下边标线,从下到上,从左到右
  703. for (int i = bmp.Height - 1; i >= 0; i--)//行
  704. {
  705. bool find = false;
  706. for (int j = left; j < bmp.Width; j++)//列
  707. {
  708. System.Drawing.Color c = bmp.GetPixel(j, i);
  709. if (!IsWhite(c))
  710. {
  711. bottom = i;
  712. find = true;
  713. break;
  714. }
  715. }
  716. if (find)
  717. {
  718. break;
  719. }
  720. }
  721. //寻找最右边的标线,从上到下,从右往左
  722. for (int i = bmp.Width - 1; i >= 0; i--)//列
  723. {
  724. bool find = false;
  725. for (int j = 0; j <= bottom; j++)//行
  726. {
  727. System.Drawing.Color c = bmp.GetPixel(i, j);
  728. if (!IsWhite(c))
  729. {
  730. right = i;
  731. find = true;
  732. break;
  733. }
  734. }
  735. if (find)
  736. {
  737. break;
  738. }
  739. }
  740. if (right - left <= 0)//zxyceshi
  741. {
  742. //克隆位图对象的一部分。
  743. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, 1, bottom - top);
  744. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  745. bmp.Dispose();
  746. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  747. return cloneBitmap;
  748. }
  749. else
  750. {
  751. //克隆位图对象的一部分。
  752. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, right - left, bottom - top);
  753. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  754. bmp.Dispose();
  755. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  756. return cloneBitmap;
  757. }
  758. }
  759. /// <summary>
  760. /// 判断是否白色和纯透明色(10点的容差)
  761. /// </summary>
  762. public static bool IsWhite(System.Drawing.Color c)
  763. {
  764. //纯透明也是白色,RGB都为255为纯白
  765. if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
  766. {
  767. return true;
  768. }
  769. return false;
  770. }
  771. #endregion
  772. }
  773. public class SaveImageModel
  774. {
  775. public string FilePath { get; set; }
  776. public BitmapEncoder encoder { get; set; }
  777. //public RenderTargetBitmap bmp { get; set; }
  778. }
  779. public class SaveModel
  780. {
  781. public int ImgWidth { get; set; }
  782. public int ImgHeight { get; set; }
  783. public BitmapEncoder encoder { get; set; }
  784. public string filePathName { get; set; }
  785. public RenderTargetBitmap bmp { get; set; }
  786. }
  787. }