PageEditTool.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing.Imaging;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows;
  14. namespace PDF_Office.Helper
  15. {
  16. public enum FileExtension
  17. {
  18. JPG = 255216,
  19. GIF = 7173,
  20. PNG = 13780,
  21. SWF = 6787,
  22. RAR = 8297,
  23. ZIP = 8075,
  24. _7Z = 55122,
  25. VALIDFILE = 9999999
  26. }
  27. /// <summary>
  28. /// 页面编辑的工具类
  29. /// </summary>
  30. public static class PageEditTool
  31. {
  32. [DllImport("user32.dll")]
  33. private static extern IntPtr SetCapture(long hWnd);
  34. [DllImport("user32.dll")]
  35. private static extern long ReleaseCapture();
  36. /// <summary>
  37. /// 打开路径并定位文件...对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"这样的,explorer.exe /select,d:xxx不认,用API整它
  38. /// </summary>
  39. /// <param name="filePath">文件绝对路径</param>
  40. [DllImport("shell32.dll", ExactSpelling = true)]
  41. private static extern void ILFree(IntPtr pidlList);
  42. [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
  43. private static extern IntPtr ILCreateFromPathW(string pszPath);
  44. [DllImport("shell32.dll", ExactSpelling = true)]
  45. private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
  46. /// <summary>
  47. /// 打开文件夹浏览,并选中一个文件(对于文件名称比较不规范的,可以用这个)
  48. /// </summary>
  49. /// <param name="filePath"></param>
  50. public static void ExplorerFile(string filePath)
  51. {
  52. try
  53. {
  54. if (!File.Exists(filePath) && !Directory.Exists(filePath))
  55. return;
  56. if (Directory.Exists(filePath))
  57. Process.Start(@"explorer.exe", "/select,\"" + filePath + "\"");
  58. else
  59. {
  60. IntPtr pidlList = ILCreateFromPathW(filePath);
  61. if (pidlList != IntPtr.Zero)
  62. {
  63. try
  64. {
  65. Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
  66. }
  67. finally
  68. {
  69. ILFree(pidlList);
  70. }
  71. }
  72. }
  73. }
  74. catch { }
  75. }
  76. /// <summary>
  77. /// 强制捕获鼠标
  78. /// </summary>
  79. /// <param name="hwd"></param>
  80. public static void DOSetCapture(long hwd)
  81. {
  82. SetCapture(hwd);
  83. }
  84. public static void DoReleaseCapture()
  85. {
  86. ReleaseCapture();
  87. }
  88. /// <summary>
  89. /// 返回文件占有的大小
  90. /// </summary>
  91. /// <param name="filePath"></param>
  92. /// <returns></returns>
  93. public static string GetFileSize(string filePath)
  94. {
  95. //判断当前路径所指向的是否为文件
  96. if (File.Exists(filePath))
  97. {
  98. //定义一个FileInfo对象,使之与filePath所指向的文件向关联,
  99. //以获取其大小
  100. FileInfo fileInfo = new FileInfo(filePath);
  101. var size = fileInfo.Length;
  102. string strSize = "";
  103. if (size < 1024)
  104. {
  105. strSize = Math.Round(size / 1024.0, 3) + " KB";
  106. }
  107. else if (size / 1024 > 1024)
  108. {
  109. strSize = Math.Round(size / 1024 / 1024.0, 1) + " MB";
  110. }
  111. else
  112. {
  113. strSize = Math.Round(size / 1024.0, 1) + " KB";
  114. }
  115. return strSize;
  116. }
  117. else
  118. {
  119. return string.Empty;
  120. }
  121. }
  122. /// <summary>
  123. /// 用照片查看器查看指定路径的图片
  124. /// </summary>
  125. /// <param name="Path">带文件名的绝对路径</param>
  126. public static void BrowsePicture(string Path)
  127. {
  128. //建立新的系统进程
  129. System.Diagnostics.Process process = new System.Diagnostics.Process();
  130. //设置文件名,此处为图片的真实路径+文件名
  131. process.StartInfo.FileName = Path;
  132. //此为关键部分。设置进程运行参数,此时为最大化窗口显示图片。
  133. process.StartInfo.Arguments = "rundll32.exe C://WINDOWS//system32//shimgvw.dll,ImageView_Fullscreen";
  134. //此项为是否使用Shell执行程序,因系统默认为true,此项也可不设,但若设置必须为true
  135. process.StartInfo.UseShellExecute = true;
  136. //此处可以更改进程所打开窗体的显示样式,可以不设
  137. process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
  138. process.Start();
  139. process.Dispose();
  140. }
  141. /// <summary>
  142. /// 校验PageRange 输入是否合法,且可返回List<int> Pages 存放的索引值
  143. /// </summary>
  144. /// <param name="pageList">返回的页面集合</param>
  145. /// <param name="pageRange">需要判断的文本</param>
  146. /// <param name="count">页面总数</param>
  147. /// <param name="enumerationSeparator">例 new char[] { ',' }</param>
  148. /// <param name="rangeSeparator">例 new char[] { '-' }</param>
  149. /// <param name="inittag"></param>
  150. /// <returns></returns>
  151. public static bool GetPagesInRange(ref List<int> pageList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  152. {
  153. string[] rangeSplit = pageRange.Split(enumerationSeparator);//根据分隔符 拆分字符串
  154. pageList.Clear();
  155. foreach (string range in rangeSplit)
  156. {
  157. int starttag = 1;
  158. if (inittag)
  159. {
  160. starttag = 0;
  161. }
  162. if (range.Contains("-"))//连续页
  163. {
  164. try
  165. {
  166. string[] limits = range.Split(rangeSeparator);//对子字符串再根据”-“ 拆分
  167. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  168. {
  169. int start = int.Parse(limits[0]);
  170. int end = int.Parse(limits[1]);
  171. if ((start < starttag) || (end > count) || (start > end))
  172. {
  173. //throw new Exception(string.Format("Invalid page(s) in range {0} - {1}", start, end));
  174. return false;
  175. }
  176. for (int i = start; i <= end; ++i)
  177. {
  178. if (pageList.Contains(i))
  179. {
  180. // throw new Exception(string.Format("Invalid page(s) in range {0} - {1}", start, end));
  181. return false;
  182. }
  183. pageList.Add(i - 1);
  184. }
  185. continue;
  186. }
  187. }
  188. catch (Exception ex)
  189. {
  190. // MessageBox.Show("请检查符号或页码范围是否正确。","提示",MessageBoxButton.OKCancel,MessageBoxImage.Warning);
  191. return false;
  192. }
  193. }
  194. int pageNr;
  195. try
  196. {
  197. // Single page
  198. pageNr = int.Parse(range);//单页
  199. }
  200. catch (Exception)//格式不正确时
  201. {
  202. return false;
  203. }
  204. if (pageNr < starttag || pageNr > count)
  205. {
  206. return false;
  207. //throw new Exception(string.Format("Invalid page {0}", pageNr));
  208. }
  209. if (pageList.Contains(pageNr))
  210. {
  211. return false;
  212. // throw new Exception(string.Format("Invalid page {0}", pageNr));
  213. }
  214. pageList.Add(pageNr - 1);
  215. }
  216. return true;
  217. }
  218. /// <summary>
  219. /// 返回指定路径的图标
  220. /// </summary>
  221. /// <param name="path"></param>
  222. /// <returns></returns>
  223. public static BitmapSource ToBitmapSource(string path)
  224. {
  225. System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
  226. System.Drawing.Bitmap bitmap = ico.ToBitmap();
  227. BitmapSource returnSource;
  228. try
  229. {
  230. returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  231. }
  232. catch
  233. {
  234. returnSource = null;
  235. }
  236. return returnSource;
  237. }
  238. public static string GetPageParmFromList(List<int> pagesList)
  239. {
  240. string pageParam = "";
  241. if (pagesList.Count != 0)
  242. {
  243. pagesList.Sort();//先对页码排序
  244. for (int i = 0; i < pagesList.Count; i++)
  245. {
  246. if (i == 0)
  247. {
  248. pageParam += pagesList[0].ToString();
  249. }
  250. else
  251. {
  252. if (pagesList[i] == pagesList[i - 1] + 1)//页码连续
  253. {
  254. if (i >= 2)
  255. {
  256. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  257. pageParam += "-";
  258. }
  259. else
  260. pageParam += "-";
  261. if (i == pagesList.Count - 1)
  262. {
  263. pageParam += pagesList[i].ToString();
  264. }
  265. }
  266. else//页码不连续时
  267. {
  268. if (i >= 2)
  269. {
  270. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  271. pageParam += pagesList[i - 1].ToString();
  272. }
  273. pageParam += "," + pagesList[i].ToString();
  274. }
  275. }
  276. }
  277. }
  278. return pageParam;
  279. }
  280. /// <summary>
  281. /// 检测文件是否重复 追加尾号
  282. /// </summary>
  283. /// <param name="path"></param>
  284. /// <returns></returns>
  285. public static string CreateFilePath(string path)
  286. {
  287. int i = 1;
  288. string oldDestName = path;
  289. do
  290. {
  291. if (File.Exists(path))
  292. {
  293. int lastDot = oldDestName.LastIndexOf('.');
  294. string fileExtension = string.Empty;
  295. string fileName = oldDestName;
  296. if (lastDot > 0)
  297. {
  298. fileExtension = fileName.Substring(lastDot);
  299. fileName = fileName.Substring(0, lastDot);
  300. }
  301. path = fileName + string.Format(@"({0})", i) + fileExtension;
  302. }
  303. ++i;
  304. } while (File.Exists(path));
  305. return path;
  306. }
  307. /// <summary>
  308. /// 检查文件夹是否重复 追加尾号
  309. /// </summary>
  310. /// <param name="path"></param>
  311. /// <returns></returns>
  312. public static string CreateFolder(string folder)
  313. {
  314. try
  315. {
  316. int i = 1;
  317. string oldDestName = folder;
  318. DirectoryInfo info = new DirectoryInfo(folder);
  319. do
  320. {
  321. info = new DirectoryInfo(folder);
  322. if (info.Exists)
  323. {
  324. string fileName = oldDestName;
  325. folder = fileName + string.Format(@"({0})", i);
  326. }
  327. ++i;
  328. } while (info.Exists);
  329. info.Create();
  330. }
  331. catch { return null; }
  332. return folder;
  333. }
  334. /// <summary>
  335. /// 文件名称是否合法
  336. /// </summary>
  337. /// <param name="fileName">文件名</param>
  338. /// <returns>返回true是合法</returns>
  339. public static bool IsValidFileName(string fileName)
  340. {
  341. try
  342. {
  343. foreach (char invalidChar in Path.GetInvalidFileNameChars())
  344. {
  345. if (fileName.Contains(invalidChar.ToString()))
  346. return false;
  347. }
  348. return true;
  349. }
  350. catch
  351. {
  352. return false;
  353. }
  354. }
  355. /// <summary>
  356. /// 悬浮提示框(气泡形式)
  357. /// </summary>
  358. /// <param name="control">显示提示的控件</param>
  359. /// <param name="tipMsg">内容</param>
  360. /// <param name="tipTitle">标题</param>
  361. /// <param name="delay">调用该函数而显示时间</param>
  362. /// <param name="autoPopDelay">悬浮控件上的显示时间</param>
  363. public static async void ShowToolTip(Control control, string tipMsg, string tipTitle = "", int delay = 2000, int autoPopDelay = 0)
  364. {
  365. if (control == null || string.IsNullOrEmpty(tipMsg))
  366. return;
  367. try
  368. {
  369. ToolTip toolTip = new ToolTip();
  370. //if (string.IsNullOrEmpty(tipTitle))
  371. // tipTitle = App.MainPageLoader.GetString("Main_HintWarningTilte");
  372. toolTip.ToolTipTitle = tipTitle;
  373. toolTip.SetToolTip(control, tipMsg);
  374. toolTip.IsBalloon = true;
  375. toolTip.ToolTipIcon = ToolTipIcon.Warning;
  376. toolTip.ShowAlways = false;
  377. toolTip.AutoPopDelay = autoPopDelay;
  378. toolTip.Show(tipMsg, control);
  379. await Task.Delay(delay);
  380. toolTip.Hide(control);
  381. }
  382. catch { }
  383. }
  384. public static BitmapImage ToBitmapImage(System.Drawing.Bitmap ImageOriginal)
  385. {
  386. System.Drawing.Bitmap ImageOriginalBase = new System.Drawing.Bitmap(ImageOriginal);
  387. BitmapImage bitmapImage = new BitmapImage();
  388. using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
  389. {
  390. //ImageOriginalBase.Save(ms, ImageOriginalBase.RawFormat);
  391. ImageOriginalBase.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  392. bitmapImage.BeginInit();
  393. bitmapImage.StreamSource = ms;
  394. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  395. bitmapImage.EndInit();
  396. bitmapImage.Freeze();
  397. }
  398. return bitmapImage;
  399. }
  400. /// <summary>
  401. /// 获取图片的旋转角度
  402. /// 获取后可以 通过bitmap的RotateFlip 回位
  403. /// </summary>
  404. /// <param name="path">文件路径</param>
  405. /// <returns></returns>
  406. public static int GetPictureRotation(string path)
  407. {
  408. int rotate = 0;
  409. using (var image = System.Drawing.Image.FromFile(path))
  410. {
  411. foreach (var prop in image.PropertyItems)
  412. {
  413. if (prop.Id == 0x112)
  414. {
  415. if (prop.Value[0] == 6)
  416. rotate = 90;
  417. if (prop.Value[0] == 8)
  418. rotate = -90;
  419. if (prop.Value[0] == 3)
  420. rotate = 180;
  421. prop.Value[0] = 1;
  422. }
  423. }
  424. }
  425. return rotate;
  426. }
  427. public static byte[] GetImageByteFromPath(string ImagePath, string fileExt, out double width, out double height)
  428. {
  429. try
  430. {
  431. #region 跟图章一样的转换方法。
  432. if (ImagePath != null && ImagePath.Length > 0 && File.Exists(ImagePath))
  433. {
  434. FileStream fileData = File.OpenRead(ImagePath);
  435. BitmapFrame frame = null;
  436. width = 0;
  437. height = 0;
  438. if (fileExt.Contains(".jpg") || fileExt.Contains(".jpeg"))
  439. {
  440. JpegBitmapDecoder decoder = (JpegBitmapDecoder)JpegBitmapDecoder.Create(fileData, BitmapCreateOptions.None, BitmapCacheOption.Default);
  441. frame = decoder.Frames[0];
  442. width = frame.Width;
  443. height = frame.Height;
  444. }
  445. else if (fileExt.Contains(".png"))
  446. {
  447. PngBitmapDecoder decoder = (PngBitmapDecoder)PngBitmapDecoder.Create(fileData, BitmapCreateOptions.None, BitmapCacheOption.Default);
  448. frame = decoder.Frames[0];
  449. width = frame.Width;
  450. height = frame.Height;
  451. }
  452. else if (fileExt.Contains(".bmp"))
  453. {
  454. BmpBitmapDecoder decoder = (BmpBitmapDecoder)BmpBitmapDecoder.Create(fileData, BitmapCreateOptions.None, BitmapCacheOption.Default);
  455. frame = decoder.Frames[0];
  456. width = frame.Width;
  457. height = frame.Height;
  458. }
  459. else//默认采用png的解码方式
  460. {
  461. BitmapDecoder decoder = BitmapDecoder.Create(fileData, BitmapCreateOptions.None, BitmapCacheOption.Default);
  462. frame = decoder.Frames[0];
  463. width = frame.Width;
  464. height = frame.Height;
  465. }
  466. if (frame != null)
  467. {
  468. var ImageArray = new byte[frame.PixelWidth * frame.PixelHeight * 4];
  469. frame.CopyPixels(ImageArray, frame.PixelWidth * 4, 0);
  470. return ImageArray;
  471. }
  472. return null;
  473. }
  474. width = 0;
  475. height = 0;
  476. return null;
  477. #endregion 跟图章一样的转换方法。
  478. }
  479. catch (Exception ex)
  480. {
  481. width = 0;
  482. height = 0;
  483. return null;
  484. }
  485. }
  486. /// <summary>
  487. /// BitmapImage 转Bitmap
  488. /// </summary>
  489. /// <param name="bitmapImage"></param>
  490. /// <param name="isPng"></param>
  491. /// <returns></returns>
  492. public static Bitmap GetBitmapByBitmapImage(BitmapImage bitmapImage, bool isPng = false)
  493. {
  494. Bitmap bitmap;
  495. MemoryStream outStream = new MemoryStream();
  496. BitmapEncoder enc = new JpegBitmapEncoder();
  497. if (isPng)
  498. {
  499. enc = new PngBitmapEncoder();
  500. }
  501. enc.Frames.Add(BitmapFrame.Create(bitmapImage));
  502. enc.Save(outStream);
  503. bitmap = new Bitmap(outStream);
  504. return bitmap;
  505. }
  506. /// <summary>
  507. /// 根据图片数据判断图片类型
  508. /// </summary>
  509. /// <param name="fileName"></param>
  510. /// <returns></returns>
  511. public static FileExtension CheckTextFile(string fileName)
  512. {
  513. FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  514. System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
  515. string fileType = string.Empty; ;
  516. try
  517. {
  518. byte data = br.ReadByte();
  519. fileType += data.ToString();
  520. data = br.ReadByte();
  521. fileType += data.ToString();
  522. FileExtension extension;
  523. try
  524. {
  525. extension = (FileExtension)Enum.Parse(typeof(FileExtension), fileType);
  526. }
  527. catch
  528. {
  529. extension = FileExtension.VALIDFILE;
  530. }
  531. return extension;
  532. }
  533. catch (Exception ex)
  534. {
  535. throw ex;
  536. }
  537. finally
  538. {
  539. if (fs != null)
  540. {
  541. fs.Close();
  542. br.Close();
  543. }
  544. }
  545. }
  546. /// <summary>
  547. /// 压缩图片到600*600以内,压缩成功后返回压缩完成的缓存路径
  548. /// 如果压缩 失败 返回原图路径
  549. /// </summary>
  550. /// <param name="filePath"></param>
  551. /// <returns></returns>
  552. public static string CompressImage(string filePath, int maxwidth = 600)
  553. {
  554. try
  555. {
  556. string sourcepath = filePath;
  557. var guid = Guid.NewGuid().ToString();
  558. string folder = Path.Combine(App.CurrentPath, "Temp");
  559. if (!Directory.Exists(folder))
  560. {
  561. Directory.CreateDirectory(folder);
  562. }
  563. var path = System.IO.Path.Combine(App.CurrentPath, "Temp", guid);
  564. Bitmap bitmap = new Bitmap(sourcepath);
  565. var b = bitmap;
  566. //bitmap.Dispose();
  567. double scale = Math.Min((double)maxwidth / b.Width, (double)maxwidth / b.Height);
  568. scale = Math.Min(scale, 1);
  569. System.Drawing.Size newsize = new System.Drawing.Size(maxwidth, maxwidth);
  570. newsize.Width = (int)(scale * b.Width);
  571. newsize.Height = (int)(scale * b.Height);
  572. if (!File.Exists(path))
  573. {
  574. if (CheckTextFile(sourcepath) == FileExtension.PNG)
  575. {
  576. using (var bp = new Bitmap(b, (int)newsize.Width, (int)newsize.Height))
  577. {
  578. bp.Save(path, ImageFormat.Png);
  579. }
  580. }
  581. else
  582. {
  583. using (var bp = new Bitmap(b, (int)newsize.Width, (int)newsize.Height))
  584. {
  585. bp.Save(path, ImageFormat.Jpeg);
  586. }
  587. }
  588. }
  589. return path;
  590. }
  591. catch
  592. {
  593. return filePath;
  594. }
  595. }
  596. }
  597. }