星火微课系统客户端
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ImageHelper.cs 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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. /// 图片帮助类 创建人:赵耀 创建时间:2018年11月1日
  14. /// </summary>
  15. public class ImageHelper
  16. {
  17. /// <summary>
  18. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  19. /// </summary>
  20. /// <param name="path">图片位置</param>
  21. /// <returns></returns>
  22. public static Bitmap ReadBitmapFile(string path)
  23. {
  24. try
  25. {
  26. if (File.Exists(path))
  27. {
  28. FileStream fs = File.OpenRead(path); //OpenRead
  29. int filelength = 0;
  30. filelength = (int)fs.Length; //获得文件长度
  31. byte[] image = new byte[filelength]; //建立一个字节数组
  32. fs.Read(image, 0, filelength); //按字节流读取
  33. System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
  34. fs.Close();
  35. Bitmap bit = new Bitmap(result);
  36. return bit;
  37. }
  38. else
  39. {
  40. return null;
  41. }
  42. }
  43. catch (Exception)
  44. {
  45. return null;
  46. }
  47. }
  48. /// <summary>
  49. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  50. /// </summary>
  51. /// <param name="path">图片位置</param>
  52. /// <returns></returns>
  53. public static Image ReadImageFile(string path)
  54. {
  55. try
  56. {
  57. if (File.Exists(path))
  58. {
  59. FileStream fs = File.OpenRead(path); //OpenRead
  60. int filelength = 0;
  61. filelength = (int)fs.Length; //获得文件长度
  62. byte[] image = new byte[filelength]; //建立一个字节数组
  63. fs.Read(image, 0, filelength); //按字节流读取
  64. System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
  65. fs.Close();
  66. return result;
  67. }
  68. else
  69. {
  70. return null;
  71. }
  72. }
  73. catch (Exception)
  74. {
  75. return null;
  76. }
  77. }
  78. /// <summary>
  79. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  80. /// </summary>
  81. /// <param name="path">图片位置</param>
  82. /// <returns></returns>
  83. public static BitmapImage ReadBitmapImageFile(string path)
  84. {
  85. BitmapImage bitmap = new BitmapImage();
  86. try
  87. {
  88. using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path)))
  89. {
  90. bitmap = new BitmapImage
  91. {
  92. DecodePixelHeight = 100
  93. };
  94. bitmap.BeginInit();
  95. bitmap.CacheOption = BitmapCacheOption.OnLoad;//设置缓存模式
  96. bitmap.StreamSource = ms;//通过StreamSource加载图片
  97. bitmap.EndInit();
  98. bitmap.Freeze();
  99. }
  100. return bitmap;
  101. }
  102. catch (Exception)
  103. {
  104. return null;
  105. }
  106. }
  107. #region 获取RGB
  108. private static Bitmap _Bitmap = null;
  109. private static StringBuilder sb = new StringBuilder();
  110. public static string GetRGB(int x, int y)
  111. {
  112. sb = new StringBuilder();
  113. try
  114. {
  115. System.Drawing.Color color = _Bitmap.GetPixel(x, y);
  116. sb.Append("RGB:(");
  117. sb.Append(color.R.ToString());
  118. sb.Append(",");
  119. sb.Append(color.G.ToString());
  120. sb.Append(",");
  121. sb.Append(color.B.ToString());
  122. sb.Append(")");
  123. }
  124. catch (Exception ex)
  125. {
  126. LogHelper.WriteErrLog("ImageHelper(GetRGB)" + ex.Message, ex);
  127. }
  128. return sb.ToString();
  129. }
  130. #endregion 获取RGB
  131. #region 截图统一方法
  132. /// <summary>
  133. /// 截图通用方法 创建人:赵耀 创建时间:2020年8月11日
  134. /// </summary>
  135. /// <param name="ScreenSize">截图的区域,设置new Rectangle(0, 0, 0, 0)为截全屏</param>
  136. /// <param name="ImageSavePath">图片存储路径,为空或null则保存到临时文件夹</param>
  137. /// <param name="IsRetImg">是否返回图片</param>
  138. /// <param name="bitmapimg">图片</param>
  139. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  140. /// <returns></returns>
  141. public static bool GetScreenshot(Rectangle ScreenSize, string ImageSavePath, long level = -1)
  142. {
  143. try
  144. {
  145. System.Drawing.Size bounds = PrimaryScreen.DESKTOP;
  146. if (string.IsNullOrEmpty(ImageSavePath))
  147. {
  148. ImageSavePath = GetTempImagePath();//如果为空则指定临时存储路径
  149. }
  150. double scaleWidth = (bounds.Width * 1.0) / SystemParameters.PrimaryScreenWidth;
  151. double scaleHeight = (bounds.Height * 1.0) / SystemParameters.PrimaryScreenHeight;
  152. int width = bounds.Width;
  153. int height = bounds.Height;
  154. if (ScreenSize.Size != new System.Drawing.Size(0, 0))
  155. {
  156. width = (int)(ScreenSize.Size.Width * scaleWidth);
  157. height = (int)(ScreenSize.Size.Height * scaleHeight);
  158. }
  159. int l = (int)(ScreenSize.X * scaleWidth);
  160. int t = (int)(ScreenSize.Y * scaleHeight);
  161. if (_Bitmap != null)
  162. {
  163. _Bitmap.Dispose();
  164. }
  165. _Bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  166. using (Graphics g = Graphics.FromImage(_Bitmap))
  167. {
  168. g.CopyFromScreen(l, t, 0, 0, _Bitmap.Size, CopyPixelOperation.SourceCopy);
  169. Compress(_Bitmap, ImageSavePath, level);
  170. }
  171. GC.Collect();
  172. return true;
  173. }
  174. catch (Exception ex)
  175. {
  176. LogHelper.WriteErrLog("【截图】(GetBitmapSource)截图失败," + ex.Message, ex);
  177. return false;
  178. }
  179. }
  180. /// <summary>
  181. /// 截图通用方法 创建人:赵耀 创建时间:2020年8月11日
  182. /// </summary>
  183. /// <param name="ScreenSize">截图的区域,设置new Rectangle(0, 0, 0, 0)为截全屏</param>
  184. /// <param name="ImageSavePath">图片存储路径,为空或null则保存到临时文件夹</param>
  185. /// <param name="IsRetImg">是否返回图片</param>
  186. /// <param name="bitmapimg">图片</param>
  187. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  188. /// <returns></returns>
  189. public static bool GetScreenshot(Rectangle ScreenSize, string ImageSavePath, bool IsRetImg, out BitmapImage bitmapimg, long level = -1)
  190. {
  191. bitmapimg = null;
  192. try
  193. {
  194. System.Drawing.Size bounds = PrimaryScreen.DESKTOP;
  195. if (string.IsNullOrEmpty(ImageSavePath))
  196. {
  197. ImageSavePath = GetTempImagePath();//如果为空则指定临时存储路径
  198. }
  199. double scaleWidth = (bounds.Width * 1.0) / SystemParameters.PrimaryScreenWidth;
  200. double scaleHeight = (bounds.Height * 1.0) / SystemParameters.PrimaryScreenHeight;
  201. int width = bounds.Width;
  202. int height = bounds.Height;
  203. if (ScreenSize.Size != new System.Drawing.Size(0, 0))
  204. {
  205. width = (int)(ScreenSize.Size.Width * scaleWidth);
  206. height = (int)(ScreenSize.Size.Height * scaleHeight);
  207. }
  208. int l = (int)(ScreenSize.X * scaleWidth);
  209. int t = (int)(ScreenSize.Y * scaleHeight);
  210. if (_Bitmap != null)
  211. {
  212. _Bitmap.Dispose();
  213. }
  214. _Bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  215. using (Graphics g = Graphics.FromImage(_Bitmap))
  216. {
  217. g.CopyFromScreen(l, t, 0, 0, _Bitmap.Size, CopyPixelOperation.SourceCopy);
  218. Compress(_Bitmap, ImageSavePath, level);
  219. }
  220. if (IsRetImg)
  221. {
  222. Uri uri = new Uri(ImageSavePath, UriKind.Absolute);
  223. bitmapimg = new BitmapImage(uri);
  224. }
  225. GC.Collect();
  226. return true;
  227. }
  228. catch (Exception ex)
  229. {
  230. LogHelper.WriteErrLog("【截图】(GetBitmapSource)截图失败," + ex.Message, ex);
  231. return false;
  232. }
  233. }
  234. /// <summary>
  235. /// 获取临时图片保存位置
  236. /// </summary>
  237. /// <returns></returns>
  238. public static string GetTempImagePath()
  239. {
  240. TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  241. string TempPath = FileToolsCommon.GetFileAbsolutePath("/temp/Screenshot/");
  242. FileToolsCommon.CreateDirectory(TempPath);
  243. TempPath += Convert.ToInt64(ts.TotalMilliseconds).ToString() + ".jpg";
  244. return TempPath;
  245. }
  246. #endregion 截图统一方法
  247. #region 图片压缩
  248. /// <summary>
  249. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  250. /// </summary>
  251. /// <param name="srcBitMap">传入的Bitmap对象</param>
  252. /// <param name="destFile">压缩后的图片保存路径</param>
  253. /// <param name="level">压缩等级,-1为config配置的值,0到100,0 最差质量,100 最佳</param>
  254. public static void Compress(Bitmap srcBitMap, string destFile, long level)
  255. {
  256. if (level <= -1)
  257. {
  258. int ImageCompressionLevel = int.Parse(FileToolsCommon.GetConfigValue("ImageCompressionLevel"));
  259. level = ImageCompressionLevel;
  260. }
  261. Stream s = new FileStream(destFile, FileMode.Create);
  262. Compress(srcBitMap, s, level);
  263. s.Close();
  264. }
  265. /// <summary>
  266. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  267. /// </summary>
  268. /// <param name="srcBitmap">传入的Bitmap对象</param>
  269. /// <param name="destStream">压缩后的Stream对象</param>
  270. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  271. public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
  272. {
  273. ImageCodecInfo myImageCodecInfo;
  274. System.Drawing.Imaging.Encoder myEncoder;
  275. EncoderParameter myEncoderParameter;
  276. EncoderParameters myEncoderParameters;
  277. //获取表示jpeg编解码器的imagecodecinfo对象
  278. myImageCodecInfo = GetEncoderInfo("image/jpeg");
  279. myEncoder = System.Drawing.Imaging.Encoder.Quality;
  280. myEncoderParameters = new EncoderParameters(1);
  281. myEncoderParameter = new EncoderParameter(myEncoder, level);
  282. myEncoderParameters.Param[0] = myEncoderParameter;
  283. srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
  284. }
  285. /// <summary>
  286. /// 获取解码器 创建人:赵耀 创建时间2020年8月11日
  287. /// </summary>
  288. /// <param name="mimeType"></param>
  289. /// <returns></returns>
  290. private static ImageCodecInfo GetEncoderInfo(string mimeType)
  291. {
  292. int j;
  293. ImageCodecInfo[] encoders;
  294. encoders = ImageCodecInfo.GetImageEncoders();
  295. for (j = 0; j < encoders.Length; ++j)
  296. {
  297. if (encoders[j].MimeType == mimeType)
  298. {
  299. return encoders[j];
  300. }
  301. }
  302. return null;
  303. }
  304. /// <summary>
  305. /// 压缩图片 -测试方法 待完善 暂无用
  306. /// </summary>
  307. /// <param name="_bitmap">原图片</param>
  308. /// <param name="dFile">压缩后保存图片地址</param>
  309. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  310. /// <param name="size">压缩后图片的最大大小</param>
  311. /// <param name="sfsc">是否是第一次调用</param>
  312. /// <returns></returns>
  313. public static bool CompressImage(Bitmap _bitmap, string dFile, int flag = 90, int size = 300)
  314. {
  315. ////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  316. //FileInfo firstFileInfo = new FileInfo(sFile);
  317. //if (sfsc == true && firstFileInfo.Length < size * 1024)
  318. //{
  319. // firstFileInfo.CopyTo(dFile);
  320. // return true;
  321. //}
  322. //Image iSource = Image.FromFile(sFile);
  323. Image iSource = _bitmap;
  324. ImageFormat tFormat = iSource.RawFormat;
  325. int dHeight = iSource.Height / 2;
  326. int dWidth = iSource.Width / 2;
  327. int sW, sH;
  328. //按比例缩放
  329. System.Drawing.Size tem_size = new System.Drawing.Size(iSource.Width, iSource.Height);
  330. if (tem_size.Width > dHeight || tem_size.Width > dWidth)
  331. {
  332. if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
  333. {
  334. sW = dWidth;
  335. sH = (dWidth * tem_size.Height) / tem_size.Width;
  336. }
  337. else
  338. {
  339. sH = dHeight;
  340. sW = (tem_size.Width * dHeight) / tem_size.Height;
  341. }
  342. }
  343. else
  344. {
  345. sW = tem_size.Width;
  346. sH = tem_size.Height;
  347. }
  348. Bitmap ob = new Bitmap(dWidth, dHeight);
  349. Graphics g = Graphics.FromImage(ob);
  350. g.Clear(System.Drawing.Color.WhiteSmoke);
  351. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  352. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  353. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  354. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  355. g.Dispose();
  356. //以下代码为保存图片时,设置压缩质量
  357. EncoderParameters ep = new EncoderParameters();
  358. long[] qy = new long[1];
  359. qy[0] = flag;//设置压缩的比例1-100
  360. EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
  361. ep.Param[0] = eParam;
  362. try
  363. {
  364. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
  365. ImageCodecInfo jpegICIinfo = null;
  366. for (int x = 0; x < arrayICI.Length; x++)
  367. {
  368. if (arrayICI[x].FormatDescription.Equals("JPEG"))
  369. {
  370. jpegICIinfo = arrayICI[x];
  371. break;
  372. }
  373. }
  374. if (jpegICIinfo != null)
  375. {
  376. if (flag > 0)
  377. {
  378. ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
  379. FileInfo fi = new FileInfo(dFile);
  380. if (fi.Length > 1024 * size)
  381. {
  382. flag -= 10;
  383. CompressImage(_bitmap, dFile, flag, size);
  384. }
  385. }
  386. //ob.Save(dFile, jpegICIinfo, ep);
  387. //FileInfo fi = new FileInfo(dFile);
  388. //bool IsAgain = false;
  389. //if (fi.Length > 1024 * size)
  390. //{
  391. // fi.CopyTo(dFile + fi.Length);
  392. // fi.Delete();
  393. // Bitmap newbitmap = ReadImageFile(dFile + fi.Length);
  394. // CompressImage(newbitmap, dFile, flag, size);
  395. // FileToolsCommon.DeleteFile(dFile + fi.Length);
  396. //}
  397. }
  398. else
  399. {
  400. ob.Save(dFile, tFormat);
  401. }
  402. return true;
  403. }
  404. catch
  405. {
  406. return false;
  407. }
  408. finally
  409. {
  410. iSource.Dispose();
  411. ob.Dispose();
  412. }
  413. }
  414. #endregion 图片压缩
  415. #region 截屏指定UI控件
  416. /// <summary>
  417. /// 保存图片
  418. /// </summary>
  419. /// <param name="ui">需要截图的UI控件</param>
  420. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  421. /// <param name="ImgWidth">转换后高</param>
  422. /// <param name="ImgHeight">转换后高</param>
  423. public static void SaveUI(FrameworkElement ui, string filePathName, int ImgWidth, int ImgHeight)
  424. {
  425. Console.WriteLine("截图的路径为:" + filePathName);
  426. try
  427. {
  428. RenderTargetBitmap bmp = new RenderTargetBitmap(
  429. (int)ui.ActualWidth,
  430. (int)ui.ActualHeight,
  431. 1 / 96, 1 / 96,
  432. PixelFormats.Default
  433. );
  434. bmp.Render(ui);
  435. BitmapEncoder encoder = new PngBitmapEncoder();
  436. encoder.Frames.Add(BitmapFrame.Create(bmp));
  437. if (ImgWidth > 0)
  438. {
  439. MemoryStream memoryStream = new MemoryStream();
  440. encoder.Save(memoryStream);
  441. Bitmap bit = new Bitmap(memoryStream, true);
  442. Bitmap Img = new Bitmap(bit, ImgWidth, ImgHeight);
  443. Img.Save(filePathName);
  444. Img.Dispose();
  445. bit.Dispose();
  446. memoryStream.Dispose();
  447. }
  448. else
  449. {
  450. using (var stream = new FileStream(filePathName, FileMode.Create))
  451. {
  452. encoder.Save(stream);
  453. }
  454. }
  455. }
  456. catch (Exception e)
  457. {
  458. Console.WriteLine(e.Message);
  459. }
  460. }
  461. public static void SaveUI2(FrameworkElement frameworkElement, string filePathName)
  462. {
  463. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  464. RenderTargetBitmap bmp = new RenderTargetBitmap((int)frameworkElement.ActualWidth, (int)frameworkElement.ActualHeight, 1 / 96, 1 / 96, PixelFormats.Default);
  465. bmp.Render(frameworkElement);
  466. BitmapEncoder encoder = new PngBitmapEncoder();
  467. encoder.Frames.Add(BitmapFrame.Create(bmp));
  468. encoder.Save(fs);
  469. fs.Close();
  470. }
  471. public static Bitmap SaveUI2Bitmap(FrameworkElement frameworkElement, int width, int height)
  472. {
  473. using (MemoryStream outStream = new MemoryStream())
  474. {
  475. RenderTargetBitmap bmp = new RenderTargetBitmap(
  476. (int)frameworkElement.ActualWidth,
  477. (int)frameworkElement.ActualHeight,
  478. 1 / 96,
  479. 1 / 96,
  480. PixelFormats.Default
  481. );
  482. bmp.Render(frameworkElement);
  483. BitmapEncoder enc = new PngBitmapEncoder();
  484. enc.Frames.Add(BitmapFrame.Create(bmp));
  485. enc.Save(outStream);
  486. System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
  487. return new Bitmap(bitmap, width, height);
  488. }
  489. }
  490. /// <summary>
  491. /// 截图转换成bitmap
  492. /// </summary>
  493. /// <param name="element"></param>
  494. /// <param name="width">默认控件宽度</param>
  495. /// <param name="height">默认控件高度</param>
  496. /// <param name="x">默认0</param>
  497. /// <param name="y">默认0</param>
  498. /// <returns></returns>
  499. public static Bitmap ToBitmap(FrameworkElement element, string filePathName, int width = 0, int height = 0, int x = 0, int y = 0)
  500. {
  501. if (width == 0) width = (int)element.ActualWidth;
  502. if (height == 0) height = (int)element.ActualHeight;
  503. var rtb = new RenderTargetBitmap(width, height, x, y, System.Windows.Media.PixelFormats.Default);
  504. rtb.Render(element);
  505. var bit = BitmapSourceToBitmap(rtb);
  506. //测试代码
  507. DirectoryInfo d = new DirectoryInfo(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Cache"));
  508. if (!d.Exists) d.Create();
  509. bit.Save(System.IO.Path.Combine(d.FullName, "控件截图.png"));
  510. return bit;
  511. }
  512. /// <summary>
  513. /// BitmapSource转Bitmap
  514. /// </summary>
  515. /// <param name="source"></param>
  516. /// <returns></returns>
  517. public static Bitmap BitmapSourceToBitmap(BitmapSource source)
  518. {
  519. return BitmapSourceToBitmap(source, source.PixelWidth, source.PixelHeight);
  520. }
  521. /// <summary>
  522. /// Convert BitmapSource to Bitmap
  523. /// </summary>
  524. /// <param name="source"></param>
  525. /// <returns></returns>
  526. public static Bitmap BitmapSourceToBitmap(BitmapSource source, int width, int height)
  527. {
  528. Bitmap bmp = null;
  529. try
  530. {
  531. System.Drawing.Imaging.PixelFormat format = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
  532. /*set the translate type according to the in param(source)*/
  533. switch (source.Format.ToString())
  534. {
  535. case "Rgb24":
  536. case "Bgr24": format = System.Drawing.Imaging.PixelFormat.Format24bppRgb; break;
  537. case "Bgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; break;
  538. case "Bgr32": format = System.Drawing.Imaging.PixelFormat.Format32bppRgb; break;
  539. case "Pbgra32": format = System.Drawing.Imaging.PixelFormat.Format32bppArgb; break;
  540. }
  541. bmp = new Bitmap(width, height, format);
  542. BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
  543. ImageLockMode.WriteOnly,
  544. format);
  545. source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
  546. bmp.UnlockBits(data);
  547. }
  548. catch
  549. {
  550. if (bmp != null)
  551. {
  552. bmp.Dispose();
  553. bmp = null;
  554. }
  555. }
  556. return bmp;
  557. }
  558. #endregion 截屏指定UI控件
  559. #region 去掉白边
  560. /// <summary>
  561. /// 裁剪图片(去掉白边)
  562. /// </summary>
  563. /// <param name="FilePath"></param>
  564. public static Bitmap CutImageWhitePart(Bitmap bmp)
  565. {
  566. //Bitmap bmp = new Bitmap(FilePath);
  567. //上左右下
  568. int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
  569. //寻找最上面的标线,从左(0)到右,从上(0)到下
  570. for (int i = 0; i < bmp.Height; i++)//行
  571. {
  572. bool find = false;
  573. for (int j = 0; j < bmp.Width; j++)//列
  574. {
  575. System.Drawing.Color c = bmp.GetPixel(j, i);
  576. if (!IsWhite(c))
  577. {
  578. top = i;
  579. find = true;
  580. break;
  581. }
  582. }
  583. if (find)
  584. {
  585. break;
  586. }
  587. }
  588. //寻找最左边的标线,从上(top位)到下,从左到右
  589. for (int i = 0; i < bmp.Width; i++)//列
  590. {
  591. bool find = false;
  592. for (int j = top; j < bmp.Height; j++)//行
  593. {
  594. System.Drawing.Color c = bmp.GetPixel(i, j);
  595. if (!IsWhite(c))
  596. {
  597. left = i;
  598. find = true;
  599. break;
  600. }
  601. }
  602. if (find)
  603. {
  604. break;
  605. }
  606. }
  607. //寻找最下边标线,从下到上,从左到右
  608. for (int i = bmp.Height - 1; i >= 0; i--)//行
  609. {
  610. bool find = false;
  611. for (int j = left; j < bmp.Width; j++)//列
  612. {
  613. System.Drawing.Color c = bmp.GetPixel(j, i);
  614. if (!IsWhite(c))
  615. {
  616. bottom = i;
  617. find = true;
  618. break;
  619. }
  620. }
  621. if (find)
  622. {
  623. break;
  624. }
  625. }
  626. //寻找最右边的标线,从上到下,从右往左
  627. for (int i = bmp.Width - 1; i >= 0; i--)//列
  628. {
  629. bool find = false;
  630. for (int j = 0; j <= bottom; j++)//行
  631. {
  632. System.Drawing.Color c = bmp.GetPixel(i, j);
  633. if (!IsWhite(c))
  634. {
  635. right = i;
  636. find = true;
  637. break;
  638. }
  639. }
  640. if (find)
  641. {
  642. break;
  643. }
  644. }
  645. if (right - left <= 0)//zxyceshi
  646. {
  647. //克隆位图对象的一部分。
  648. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, 1, bottom - top);
  649. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  650. bmp.Dispose();
  651. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  652. return cloneBitmap;
  653. }
  654. else
  655. {
  656. //克隆位图对象的一部分。
  657. System.Drawing.Rectangle cloneRect = new System.Drawing.Rectangle(left, top, right - left, bottom - top);
  658. Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
  659. bmp.Dispose();
  660. //cloneBitmap.Save(@"d:\123.png", ImageFormat.Png);
  661. return cloneBitmap;
  662. }
  663. }
  664. /// <summary>
  665. /// 判断是否白色和纯透明色(10点的容差)
  666. /// </summary>
  667. public static bool IsWhite(System.Drawing.Color c)
  668. {
  669. //纯透明也是白色,RGB都为255为纯白
  670. if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
  671. {
  672. return true;
  673. }
  674. return false;
  675. }
  676. #endregion 去掉白边
  677. }
  678. public class SaveImageModel
  679. {
  680. public string FilePath { get; set; }
  681. public BitmapEncoder encoder { get; set; }
  682. //public RenderTargetBitmap bmp { get; set; }
  683. }
  684. public class SaveModel
  685. {
  686. public int ImgWidth { get; set; }
  687. public int ImgHeight { get; set; }
  688. public BitmapEncoder encoder { get; set; }
  689. public string filePathName { get; set; }
  690. public RenderTargetBitmap bmp { get; set; }
  691. }
  692. }