星火微课系统客户端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImageHelper.cs 26KB

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