星火微课系统客户端
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 28KB

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