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

ImageHelper.cs 29KB

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