DocumentWorkspace.cs 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097
  1. using PaintDotNet.Actions;
  2. using PaintDotNet.Annotation.Enum;
  3. using PaintDotNet.Base.CommTool;
  4. using PaintDotNet.Base.SettingModel;
  5. using PaintDotNet.SystemLayer;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Drawing;
  10. using System.Drawing.Imaging;
  11. using System.IO;
  12. using System.Reflection;
  13. using System.Runtime.Serialization;
  14. using System.Security;
  15. using System.Threading;
  16. using System.Windows.Forms;
  17. using PaintDotNet.SystemLayer.FileDlgExtenders.FileDialogExtenders;
  18. using PaintDotNet.Annotation.Measure;
  19. using PaintDotNet.Base.Functionodel;
  20. using OpenCvSharp;
  21. using PaintDotNet.Setting;
  22. using PaintDotNet.ImageLabel;
  23. using PaintDotNet.Measuring;
  24. using Metis.Measuring;
  25. using PaintDotNet.DbOpreate.DbModel;
  26. using PaintDotNet.Annotation;
  27. namespace PaintDotNet
  28. {
  29. internal class DocumentWorkspace : DocumentView
  30. {
  31. /// <summary>
  32. /// 主控件
  33. /// </summary>
  34. private AppWorkspace appWorkspace;
  35. /// <summary>
  36. /// 缩放模式
  37. /// </summary>
  38. private ZoomBasis zoomBasis;
  39. /// <summary>
  40. /// 文件路径
  41. /// </summary>
  42. public string filePath = null;
  43. /// <summary>
  44. /// 文件名
  45. /// </summary>
  46. public string fileText = null;
  47. /// <summary>
  48. /// 文件类型
  49. /// </summary>
  50. private FileType fileType = null;
  51. /// <summary>
  52. /// 文件 - 批量保存自动配置
  53. /// </summary>
  54. public BatchSaveAutoModel batchSaveAutoModel;
  55. private SaveConfigToken saveConfigToken = null;
  56. private ImageResource statusIcon = null;
  57. public TreeView oldDrawTreeView;
  58. public ZipHandleHelper zipHandleHelper;//zip对象
  59. public ZipXmlModel zipXmlModel;//zip的图片列表xml
  60. public string picName;//zip包当前显示的图片名
  61. public bool needBackup = true;//判断图片是否需要备份
  62. private bool openInScriptRunning = false;//判断图片是否脚本执行过程中打开
  63. #region 底部按钮选中状态
  64. /// <summary>
  65. /// 最佳
  66. /// </summary>
  67. public bool best = false;
  68. /// <summary>
  69. /// 最大最小
  70. /// </summary>
  71. public bool maxMin = false;
  72. /// <summary>
  73. /// 原始状态
  74. /// </summary>
  75. public bool origin = true;
  76. /// <summary>
  77. /// 伽马0.45
  78. /// </summary>
  79. public bool gamma45 = false;
  80. /// <summary>
  81. /// 移动模式
  82. /// </summary>
  83. public bool mobileMode = false;
  84. /// <summary>
  85. /// 指针模式
  86. /// </summary>
  87. public bool cursorMode = true;
  88. /// <summary>
  89. /// MainForm
  90. /// </summary>
  91. #endregion
  92. public int buttonType;
  93. /// <summary>
  94. /// 更新按钮文字
  95. /// </summary>
  96. /// <param name="buttonName"></param>
  97. public void UpdateDw2buttonName(string buttonName)
  98. {
  99. if (appWorkspace != null)
  100. appWorkspace.toolBar.DocumentStrip.SetDw2buttonName(this, buttonName);
  101. }
  102. public ImageResource StatusIcon
  103. {
  104. get
  105. {
  106. return this.statusIcon;
  107. }
  108. }
  109. /// <summary>
  110. /// 判断图片是否脚本执行过程中打开
  111. /// </summary>
  112. public bool OpenInScriptRunning
  113. {
  114. set
  115. {
  116. this.openInScriptRunning = value;
  117. }
  118. get
  119. {
  120. return this.openInScriptRunning;
  121. }
  122. }
  123. public string StatusText
  124. {
  125. get
  126. {
  127. if (!string.IsNullOrEmpty(filePath))
  128. {
  129. try
  130. {
  131. FileInfo fi = new FileInfo(filePath);
  132. return fi.CreationTime + "、" + FileOperationHelper.GetLength(fi.Length) + "、" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Width + "*" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Height;
  133. }
  134. catch (Exception)
  135. {
  136. }
  137. }
  138. return "";
  139. }
  140. }
  141. public event EventHandler StatusChanged;
  142. protected virtual void OnStatusChanged()
  143. {
  144. if (StatusChanged != null)
  145. {
  146. StatusChanged(this, EventArgs.Empty);
  147. }
  148. }
  149. protected override void OnSizeChanged(EventArgs e)
  150. {
  151. PerformLayout();
  152. base.OnSizeChanged(e);
  153. }
  154. protected override void OnLayout(LayoutEventArgs e)
  155. {
  156. if (this.zoomBasis == ZoomBasis.FitToWindow)
  157. {
  158. ZoomToWindow();
  159. // This bizarre ordering of setting PanelAutoScroll prevents some very weird layout/scroll-without-scrollbars stuff.
  160. PanelAutoScroll = true;
  161. PanelAutoScroll = false;
  162. }
  163. base.OnLayout(e);
  164. }
  165. protected override void OnResize(EventArgs e)
  166. {
  167. if (this.zoomBasis == ZoomBasis.FitToWindow)
  168. {
  169. PerformLayout();
  170. }
  171. base.OnResize(e);
  172. }
  173. protected override string[] startUpRules(Dictionary<MeasurementUnit, double> rules)
  174. {
  175. string[] result = new string[5];
  176. result[0] = Startup.instance.measurementUnit.ToString();
  177. result[1] = InvariantData.unitsDictionary[(int)Startup.instance.measurementUnit];
  178. result[2] = InvariantData.unitSymbolsDictionary[(int)Startup.instance.measurementUnit];
  179. if (rules != null)
  180. {
  181. result[3] = (rules[Startup.instance.measurementUnit]).ToString();
  182. result[4] = (rules[MeasurementUnit.Micron]).ToString();
  183. }
  184. else
  185. {
  186. result[3] = (Startup.instance.rules[Startup.instance.measurementUnit]).ToString();
  187. result[4] = (Startup.instance.rules[MeasurementUnit.Micron]).ToString();
  188. }
  189. return result;
  190. }
  191. protected override List<mic_rulers> Mic_rulersAll()
  192. {
  193. return Startup.instance.mic_rulersAll;
  194. }
  195. public DocumentWorkspace(AppWorkspace appWorkspace)
  196. {
  197. this.AppWorkspaceTop = appWorkspace;
  198. this.InitToolsAndManager();
  199. InitializeComponent();
  200. this.ShowContextMenuStrip1();
  201. this.panel.MouseDown += new MouseEventHandler(this.ShowContextMenuStrip2);
  202. this.RulersEnabled = Settings.CurrentUser.GetBoolean(SettingNames.Rulers, true);
  203. this.zoomBasis = ZoomBasis.FitToWindow;
  204. }
  205. private void ShowContextMenuStrip2(object sender, MouseEventArgs e)
  206. {
  207. if (e.Button == MouseButtons.Right)
  208. this.ShowContextMenuStrip1();
  209. }
  210. protected override void OnUnitsChanged()
  211. {
  212. base.OnUnitsChanged();
  213. }
  214. private void InitializeComponent()
  215. {
  216. }
  217. protected override void Dispose(bool disposing)
  218. {
  219. base.Dispose(disposing);
  220. }
  221. public override void ZoomIn()
  222. {
  223. this.ZoomBasis = ZoomBasis.ScaleFactor;
  224. base.ZoomIn();
  225. }
  226. public override void ZoomIn(double factor)
  227. {
  228. this.ZoomBasis = ZoomBasis.ScaleFactor;
  229. base.ZoomIn(factor);
  230. }
  231. public override void ZoomOut()
  232. {
  233. this.ZoomBasis = ZoomBasis.ScaleFactor;
  234. base.ZoomOut();
  235. }
  236. public override void ZoomOut(double factor)
  237. {
  238. this.ZoomBasis = ZoomBasis.ScaleFactor;
  239. base.ZoomOut(factor);
  240. }
  241. public event EventHandler ZoomBasisChanging;
  242. protected virtual void OnZoomBasisChanging()
  243. {
  244. if (ZoomBasisChanging != null)
  245. {
  246. ZoomBasisChanging(this, EventArgs.Empty);
  247. }
  248. }
  249. public event EventHandler ZoomBasisChanged;
  250. protected virtual void OnZoomBasisChanged()
  251. {
  252. if (ZoomBasisChanged != null)
  253. {
  254. ZoomBasisChanged(this, EventArgs.Empty);
  255. }
  256. }
  257. public ZoomBasis ZoomBasis
  258. {
  259. get
  260. {
  261. return this.zoomBasis;
  262. }
  263. set
  264. {
  265. if (this.zoomBasis != value)
  266. {
  267. OnZoomBasisChanging();
  268. this.zoomBasis = value;
  269. switch (this.zoomBasis)
  270. {
  271. //合适大小(完整显示图像)
  272. case ZoomBasis.FitToWindow:
  273. ZoomToWindow();
  274. // Enable PanelAutoScroll only long enough to recenter the view
  275. PanelAutoScroll = true;
  276. PanelAutoScroll = false;
  277. // this would be unset by the scalefactor changes in ZoomToWindow
  278. this.zoomBasis = ZoomBasis.FitToWindow;
  279. break;
  280. //实际大小
  281. case ZoomBasis.ScaleFactor:
  282. PanelAutoScroll = true;
  283. break;
  284. //合适宽度
  285. case ZoomBasis.FitToWidth:
  286. ZoomToWidth();
  287. PanelAutoScroll = true;
  288. this.zoomBasis = ZoomBasis.FitToWidth;
  289. break;
  290. //合适高度
  291. case ZoomBasis.FitToHeight:
  292. ZoomToHeight();
  293. PanelAutoScroll = true;
  294. this.zoomBasis = ZoomBasis.FitToHeight;
  295. break;
  296. default:
  297. throw new InvalidEnumArgumentException();
  298. }
  299. OnZoomBasisChanged();
  300. }
  301. }
  302. }
  303. protected override void HandleMouseWheel(Control sender, MouseEventArgs e)
  304. {
  305. if (Control.ModifierKeys == Keys.Control)
  306. {
  307. double mouseDelta = (double)e.Delta / 120.0f;
  308. Rectangle visibleDocBoundsStart = this.VisibleDocumentBounds;
  309. System.Drawing.Point mouseDocPt = this.MouseToDocument(sender, new System.Drawing.Point(e.X, e.Y));
  310. RectangleF visibleDocDocRect1 = this.VisibleDocumentRectangleF;
  311. PointF mouseNPt = new PointF(
  312. (mouseDocPt.X - visibleDocDocRect1.X) / visibleDocDocRect1.Width,
  313. (mouseDocPt.Y - visibleDocDocRect1.Y) / visibleDocDocRect1.Height);
  314. Rectangle rc = this.PanelClientRectangle;
  315. int width = this.SurfaceScrollableWidth;
  316. int height = this.SurfaceScrollableHeight;
  317. //获取鼠标在图像中的坐标定位
  318. double originX = 0.5;
  319. double originY = 0.5;
  320. double ptxInDoc = mouseDocPt.X * this.ScaleRatio;
  321. double ptyInDoc = mouseDocPt.Y * this.ScaleRatio;
  322. if (rc.Width < width)
  323. {
  324. originX = (ptxInDoc + this.PanelScrollPosition.X - 0.0) / width;
  325. }
  326. if (rc.Height < height)
  327. {
  328. originY = (ptyInDoc + this.PanelScrollPosition.Y - 0.0) / height;
  329. }
  330. const double factor = 1.12;
  331. double mouseFactor = Math.Pow(factor, Math.Abs(mouseDelta));
  332. if (e.Delta > 0)
  333. {
  334. this.ZoomIn(mouseFactor);
  335. }
  336. else if (e.Delta < 0)
  337. {
  338. this.ZoomOut(mouseFactor);
  339. }
  340. RectangleF visibleDocDocRect2 = this.VisibleDocumentRectangleF;
  341. PointF scrollPt2 = new PointF(
  342. mouseDocPt.X - visibleDocDocRect2.Width * mouseNPt.X,
  343. mouseDocPt.Y - visibleDocDocRect2.Height * mouseNPt.Y);
  344. this.DocumentScrollPositionF = scrollPt2;
  345. int width2 = this.SurfaceScrollableWidth;
  346. int height2 = this.SurfaceScrollableHeight;
  347. if ((rc.Width < width2 || rc.Height < height2) && (rc.Width < width || rc.Height < height))
  348. {
  349. //根据鼠标在图像中的坐标重新定位放大后的图像
  350. this.PanelScrollPosition = new System.Drawing.Point(
  351. (int)(width2 * originX - ptxInDoc + 0),
  352. (int)(height2 * originY - ptyInDoc + 0));
  353. }
  354. else if (rc.Width < width2 || rc.Height < height2)
  355. {
  356. this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 0, (int)(height2 - rc.Height) / 2 + 0);
  357. }
  358. else
  359. {
  360. this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 0, (int)(height2 - rc.Height) / 2 + 0);
  361. }
  362. Rectangle visibleDocBoundsEnd = this.VisibleDocumentBounds;
  363. if (visibleDocBoundsEnd != visibleDocBoundsStart)
  364. {
  365. // Make sure the screen updates, otherwise it can get a little funky looking
  366. this.Update();
  367. }
  368. }
  369. base.HandleMouseWheel(sender, e);
  370. }
  371. public void UpdateAuxiliaryLineEnabled()
  372. {
  373. this.AuxiliaryLineEnabled = this.AuxiliaryLineEnabled;
  374. }
  375. public void UpdateGridLineEnabled()
  376. {
  377. this.GridLineEnabled = this.GridLineEnabled;
  378. }
  379. protected override void OnLoad(EventArgs e)
  380. {
  381. if (this.appWorkspace == null)
  382. {
  383. throw new InvalidOperationException("Must set the Workspace property");
  384. }
  385. base.OnLoad(e);
  386. }
  387. public event EventHandler ActiveLayerChanging;
  388. protected void OnLayerChanging()
  389. {
  390. if (ActiveLayerChanging != null)
  391. {
  392. ActiveLayerChanging(this, EventArgs.Empty);
  393. }
  394. }
  395. public event EventHandler ActiveLayerChanged;
  396. protected void OnLayerChanged()
  397. {
  398. this.Focus();
  399. if (ActiveLayerChanged != null)
  400. {
  401. ActiveLayerChanged(this, EventArgs.Empty);
  402. }
  403. }
  404. public event EventHandler ToolChanging;
  405. protected void OnToolChanging()
  406. {
  407. if (ToolChanging != null)
  408. {
  409. ToolChanging(this, EventArgs.Empty);
  410. }
  411. }
  412. public event EventHandler ToolChanged;
  413. protected void OnToolChanged()
  414. {
  415. if (ToolChanged != null)
  416. {
  417. ToolChanged(this, EventArgs.Empty);
  418. }
  419. }
  420. public AppWorkspace AppWorkspace
  421. {
  422. get
  423. {
  424. return this.appWorkspace;
  425. }
  426. set
  427. {
  428. this.appWorkspace = value;
  429. }
  430. }
  431. public event EventHandler FilePathChanged;
  432. protected virtual void OnFilePathChanged()
  433. {
  434. if (FilePathChanged != null)
  435. {
  436. FilePathChanged(this, EventArgs.Empty);
  437. }
  438. }
  439. public string FilePath
  440. {
  441. get
  442. {
  443. return this.filePath;
  444. }
  445. }
  446. public string GetFriendlyName()
  447. {
  448. string friendlyName;
  449. if (this.filePath != null)
  450. {
  451. friendlyName = Path.GetFileName(this.filePath);
  452. }
  453. else if (this.fileText != null)
  454. {
  455. friendlyName = this.fileText;
  456. }
  457. else
  458. {
  459. friendlyName = PdnResources.GetString("Untitled.FriendlyName");
  460. }
  461. return friendlyName;
  462. }
  463. public FileType FileType
  464. {
  465. get
  466. {
  467. return this.fileType;
  468. }
  469. }
  470. public event EventHandler SaveOptionsChanged;
  471. protected virtual void OnSaveOptionsChanged()
  472. {
  473. if (SaveOptionsChanged != null)
  474. {
  475. SaveOptionsChanged(this, EventArgs.Empty);
  476. }
  477. }
  478. /// <summary>
  479. /// Sets the FileType and SaveConfigToken parameters that are used if the
  480. /// user chooses "Save" from the File menu. These are not used by the
  481. /// DocumentControl class and should be used by whoever actually goes
  482. /// to save the Document instance.
  483. /// </summary>
  484. /// <param name="fileType"></param>
  485. /// <param name="saveParameters"></param>
  486. public void SetDocumentSaveOptions(string newFilePath, FileType newFileType, SaveConfigToken newSaveConfigToken)
  487. {
  488. this.filePath = newFilePath;
  489. OnFilePathChanged();
  490. this.fileType = newFileType;
  491. if (newSaveConfigToken == null)
  492. {
  493. this.saveConfigToken = null;
  494. }
  495. else
  496. {
  497. this.saveConfigToken = (SaveConfigToken)newSaveConfigToken.Clone();
  498. }
  499. OnSaveOptionsChanged();
  500. }
  501. public void GetDocumentSaveOptions(out string filePathResult, out FileType fileTypeResult, out SaveConfigToken saveConfigTokenResult)
  502. {
  503. filePathResult = this.filePath;
  504. fileTypeResult = this.fileType;
  505. if (this.saveConfigToken == null)
  506. {
  507. saveConfigTokenResult = null;
  508. }
  509. else
  510. {
  511. saveConfigTokenResult = (SaveConfigToken)this.saveConfigToken.Clone();
  512. }
  513. }
  514. /// <summary>
  515. /// Updates any pertinent EXIF tags, such as "Creation Software", to be
  516. /// relevant or up-to-date.
  517. /// </summary>
  518. /// <param name="document"></param>
  519. private void UpdateExifTags(Document document)
  520. {
  521. // I have verified that other image editing software overwrites this tag,
  522. // and does not just add it when it does not exist.
  523. PropertyItem pi = Exif.CreateAscii(ExifTagID.Software, PdnInfo.GetProductName(false));
  524. document.Metadata.ReplaceExifValues(ExifTagID.Software, new PropertyItem[1] { pi });
  525. }
  526. private ZoomBasis savedZb;
  527. private ScaleFactor savedSf;
  528. protected override void OnDocumentChanging(Document newDocument)
  529. {
  530. base.OnDocumentChanging(newDocument);
  531. this.savedZb = this.ZoomBasis;
  532. this.savedSf = ScaleFactor;
  533. if (newDocument != null)
  534. {
  535. UpdateExifTags(newDocument);
  536. }
  537. }
  538. protected override void OnDocumentChanged()
  539. {
  540. if (this.Document != null)
  541. {
  542. bool oldDirty = this.Document.Dirty;
  543. this.Document.Invalidate();
  544. this.Document.Dirty = oldDirty;
  545. this.ZoomBasis = this.savedZb;
  546. if (this.savedZb == ZoomBasis.ScaleFactor)
  547. {
  548. ScaleFactor = this.savedSf;
  549. }
  550. }
  551. AutoScrollPosition = new System.Drawing.Point(0, 0);
  552. base.OnDocumentChanged();
  553. }
  554. /// <summary>
  555. /// Takes the current Document from this DocumentWorkspace instance and adds it to the MRU list.
  556. /// </summary>
  557. /// <param name="fileName"></param>
  558. public void AddToMruList()
  559. {
  560. string fullFileName = Path.GetFullPath(this.FilePath);
  561. MostRecentFile mrf = new MostRecentFile(fullFileName, null);
  562. if (AppWorkspace.MostRecentFiles.Contains(fullFileName))
  563. {
  564. AppWorkspace.MostRecentFiles.Remove(fullFileName);
  565. }
  566. AppWorkspace.MostRecentFiles.Add(mrf);
  567. AppWorkspace.MostRecentFiles.SaveMruList();
  568. }
  569. /// <summary>
  570. /// Shows an OpenFileDialog or SaveFileDialog and populates the InitialDirectory from the global
  571. /// settings repository if possible.
  572. /// </summary>
  573. /// <param name="fd">The FileDialog to show.</param>
  574. /// <remarks>
  575. /// The FileDialog should already have its InitialDirectory populated as a suggestion of where to start.
  576. /// </remarks>
  577. public static DialogResult ShowFileDialog(Control owner, IFileDialog fd)
  578. {
  579. string initialDirectory = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, fd.InitialDirectory);
  580. bool dirExists = false;
  581. try
  582. {
  583. DirectoryInfo dirInfo = new DirectoryInfo(initialDirectory);
  584. using (new WaitCursorChanger(owner))
  585. {
  586. dirExists = dirInfo.Exists;
  587. if (!dirInfo.Exists)
  588. {
  589. initialDirectory = fd.InitialDirectory;
  590. }
  591. }
  592. }
  593. catch (Exception)
  594. {
  595. initialDirectory = fd.InitialDirectory;
  596. }
  597. fd.InitialDirectory = initialDirectory;
  598. OurFileDialogUICallbacks ouc = new OurFileDialogUICallbacks();
  599. DialogResult result = fd.ShowDialog(owner, ouc);
  600. if (result == DialogResult.OK)
  601. {
  602. string fileName;
  603. if (fd is IFileOpenDialog)
  604. {
  605. string[] fileNames = ((IFileOpenDialog)fd).FileNames;
  606. if (fileNames.Length > 0)
  607. {
  608. fileName = fileNames[0];
  609. }
  610. else
  611. {
  612. fileName = null;
  613. }
  614. }
  615. else if (fd is IFileSaveDialog)
  616. {
  617. fileName = ((IFileSaveDialog)fd).FileName;
  618. }
  619. else
  620. {
  621. throw new InvalidOperationException();
  622. }
  623. if (fileName != null)
  624. {
  625. string newDir = Path.GetDirectoryName(fileName);
  626. Settings.CurrentUser.SetString(SettingNames.LastFileDialogDirectory, newDir);
  627. }
  628. else
  629. {
  630. throw new FileNotFoundException();
  631. }
  632. }
  633. return result;
  634. }
  635. private sealed class OurFileDialogUICallbacks
  636. : IFileDialogUICallbacks
  637. {
  638. public FileOverwriteAction ShowOverwritePrompt(IWin32Window owner, string pathName)
  639. {
  640. FileOverwriteAction returnVal;
  641. string title = PdnResources.GetString("SaveAs.OverwriteConfirmation.Title");
  642. string textFormat = PdnResources.GetString("SaveAs.OverwriteConfirmation.Text.Format");
  643. string fileName;
  644. try
  645. {
  646. fileName = Path.GetFileName(pathName);
  647. }
  648. catch (Exception)
  649. {
  650. fileName = pathName;
  651. }
  652. string text = string.Format(textFormat, fileName);
  653. DialogResult result = MessageBox.Show(owner, text, title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
  654. switch (result)
  655. {
  656. case DialogResult.Yes:
  657. returnVal = FileOverwriteAction.Overwrite;
  658. break;
  659. case DialogResult.No:
  660. returnVal = FileOverwriteAction.Cancel;
  661. break;
  662. default:
  663. throw new InvalidEnumArgumentException();
  664. }
  665. return returnVal;
  666. }
  667. public bool ShowError(IWin32Window owner, string filePath, Exception ex)
  668. {
  669. if (ex is PathTooLongException)
  670. {
  671. string title = PdnInfo.GetBareProductName();
  672. string message = PdnResources.GetString("FileDialog.PathTooLongException.Message");
  673. MessageBox.Show(owner, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
  674. return true;
  675. }
  676. else
  677. {
  678. return false;
  679. }
  680. }
  681. public IFileTransferProgressEvents CreateFileTransferProgressEvents()
  682. {
  683. return new OurProgressEvents();
  684. }
  685. }
  686. private sealed class OurProgressEvents
  687. : IFileTransferProgressEvents
  688. {
  689. private TransferProgressDialog progressDialog;
  690. private ICancelable cancelSink;
  691. private int itemCount = 0;
  692. private int itemOrdinal = 0;
  693. private string itemName = string.Empty;
  694. private long totalWork;
  695. private long totalProgress;
  696. private const int maxPBValue = 200; // granularity of progress bar. 100 means 1%, 200 means 0.5%, etc.
  697. private bool cancelRequested = false;
  698. private ManualResetEvent operationEnded = new ManualResetEvent(false);
  699. public OurProgressEvents()
  700. {
  701. }
  702. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "cancelSink")]
  703. public void BeginOperation(IWin32Window owner, EventHandler callWhenUIShown, ICancelable cancelSink)
  704. {
  705. if (this.progressDialog != null)
  706. {
  707. throw new InvalidOperationException("Operation already in progress");
  708. }
  709. this.progressDialog = new TransferProgressDialog();
  710. this.progressDialog.Text = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.TransferProgress.Title");
  711. this.progressDialog.Icon = Utility.ImageToIcon(PdnResources.GetImageResource("Icons.MenuFileOpenIcon.png").Reference);
  712. this.progressDialog.Title = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Initializing");
  713. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
  714. this.progressDialog.ProgressBar.Maximum = maxPBValue;
  715. this.progressDialog.CancelClicked +=
  716. delegate (object sender, EventArgs e)
  717. {
  718. this.cancelRequested = true;
  719. this.cancelSink.RequestCancel();
  720. UpdateUI();
  721. };
  722. EventHandler progressDialog_Shown =
  723. delegate (object sender, EventArgs e)
  724. {
  725. callWhenUIShown(this, EventArgs.Empty);
  726. };
  727. this.cancelSink = cancelSink;
  728. this.itemOrdinal = 0;
  729. this.cancelRequested = false;
  730. this.itemName = string.Empty;
  731. this.itemCount = 0;
  732. this.itemOrdinal = 0;
  733. this.totalProgress = 0;
  734. this.totalWork = 0;
  735. this.progressDialog.Shown += progressDialog_Shown;
  736. this.progressDialog.ShowDialog(owner);
  737. this.progressDialog.Shown -= progressDialog_Shown;
  738. this.progressDialog.Dispose();
  739. this.progressDialog = null;
  740. this.cancelSink = null;
  741. }
  742. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemCount")]
  743. public void SetItemCount(int itemCount)
  744. {
  745. if (this.progressDialog.InvokeRequired)
  746. {
  747. this.progressDialog.BeginInvoke(new Procedure<int>(SetItemCount), new object[] { itemCount });
  748. }
  749. else
  750. {
  751. this.itemCount = itemCount;
  752. UpdateUI();
  753. }
  754. }
  755. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemOrdinal")]
  756. public void SetItemOrdinal(int itemOrdinal)
  757. {
  758. if (this.progressDialog.InvokeRequired)
  759. {
  760. this.progressDialog.BeginInvoke(new Procedure<int>(SetItemOrdinal), new object[] { itemOrdinal });
  761. }
  762. else
  763. {
  764. this.itemOrdinal = itemOrdinal;
  765. this.totalWork = 0;
  766. this.totalProgress = 0;
  767. UpdateUI();
  768. }
  769. }
  770. public void SetItemInfo(string itemInfo)
  771. {
  772. if (this.progressDialog.InvokeRequired)
  773. {
  774. this.progressDialog.BeginInvoke(new Procedure<string>(SetItemInfo), new object[] { itemInfo });
  775. }
  776. else
  777. {
  778. this.itemName = itemInfo;
  779. UpdateUI();
  780. }
  781. }
  782. public void BeginItem()
  783. {
  784. if (this.progressDialog.InvokeRequired)
  785. {
  786. this.progressDialog.BeginInvoke(new Procedure(BeginItem), null);
  787. }
  788. else
  789. {
  790. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
  791. }
  792. }
  793. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalWork")]
  794. public void SetItemWorkTotal(long totalWork)
  795. {
  796. if (this.progressDialog.InvokeRequired)
  797. {
  798. this.progressDialog.BeginInvoke(new Procedure<long>(SetItemWorkTotal), new object[] { totalWork });
  799. }
  800. else
  801. {
  802. this.totalWork = totalWork;
  803. UpdateUI();
  804. }
  805. }
  806. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalProgress")]
  807. public void SetItemWorkProgress(long totalProgress)
  808. {
  809. if (this.progressDialog.InvokeRequired)
  810. {
  811. this.progressDialog.BeginInvoke(new Procedure<long>(SetItemWorkProgress), new object[] { totalProgress });
  812. }
  813. else
  814. {
  815. this.totalProgress = totalProgress;
  816. UpdateUI();
  817. }
  818. }
  819. public void EndItem(WorkItemResult result)
  820. {
  821. if (this.progressDialog.InvokeRequired)
  822. {
  823. this.progressDialog.BeginInvoke(new Procedure<WorkItemResult>(EndItem), new object[] { result });
  824. }
  825. else
  826. {
  827. }
  828. }
  829. public void EndOperation(OperationResult result)
  830. {
  831. if (this.progressDialog.InvokeRequired)
  832. {
  833. this.progressDialog.BeginInvoke(new Procedure<OperationResult>(EndOperation), new object[] { result });
  834. }
  835. else
  836. {
  837. this.progressDialog.Close();
  838. }
  839. }
  840. public WorkItemFailureAction ReportItemFailure(Exception ex)
  841. {
  842. if (this.progressDialog.InvokeRequired)
  843. {
  844. object result = this.progressDialog.Invoke(
  845. new Function<WorkItemFailureAction, Exception>(ReportItemFailure),
  846. new object[] { ex });
  847. return (WorkItemFailureAction)result;
  848. }
  849. else
  850. {
  851. WorkItemFailureAction result;
  852. result = ShowFileTransferFailedDialog(ex);
  853. return result;
  854. }
  855. }
  856. private WorkItemFailureAction ShowFileTransferFailedDialog(Exception ex)
  857. {
  858. WorkItemFailureAction result;
  859. Icon formIcon = this.progressDialog.Icon;
  860. string formTitle = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.Title");
  861. Image taskImage = PdnResources.GetImageResource("Icons.WarningIcon.png").Reference;
  862. string introTextFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.IntroText.Format");
  863. string introText = string.Format(introTextFormat, ex.Message);
  864. TaskButton retryTB = new TaskButton(
  865. PdnResources.GetImageResource("Icons.MenuImageRotate90CWIcon.png").Reference,
  866. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ActionText"),
  867. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ExplanationText"));
  868. TaskButton skipTB = new TaskButton(
  869. PdnResources.GetImageResource("Icons.HistoryFastForwardIcon.png").Reference,
  870. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ActionText"),
  871. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ExplanationText"));
  872. TaskButton cancelTB = new TaskButton(
  873. PdnResources.GetImageResource("Icons.CancelIcon.png").Reference,
  874. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ActionText"),
  875. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ExplanationText"));
  876. List<TaskButton> taskButtons = new List<TaskButton>();
  877. taskButtons.Add(retryTB);
  878. // Only have the Skip button if there is more than 1 item being transferred.
  879. // If only 1 item is begin transferred, Skip and Cancel are essentially synonymous.
  880. if (this.itemCount > 1)
  881. {
  882. taskButtons.Add(skipTB);
  883. }
  884. taskButtons.Add(cancelTB);
  885. int width96 = (TaskDialog.DefaultPixelWidth96Dpi * 4) / 3; // 33% wider
  886. TaskButton clickedTB = TaskDialog.Show(
  887. this.progressDialog,
  888. formIcon,
  889. formTitle,
  890. taskImage,
  891. true,
  892. introText,
  893. taskButtons.ToArray(),
  894. retryTB,
  895. cancelTB,
  896. width96,
  897. false,
  898. 0,
  899. out bool unuse);
  900. if (clickedTB == retryTB)
  901. {
  902. result = WorkItemFailureAction.RetryItem;
  903. }
  904. else if (clickedTB == skipTB)
  905. {
  906. result = WorkItemFailureAction.SkipItem;
  907. }
  908. else
  909. {
  910. result = WorkItemFailureAction.CancelOperation;
  911. }
  912. return result;
  913. }
  914. private void UpdateUI()
  915. {
  916. int itemCount2 = Math.Max(1, this.itemCount);
  917. double startValue = (double)this.itemOrdinal / (double)itemCount2;
  918. double endValue = (double)(this.itemOrdinal + 1) / (double)itemCount2;
  919. long totalWork2 = Math.Max(1, this.totalWork);
  920. double lerp = (double)this.totalProgress / (double)totalWork2;
  921. double newValue = Utility.Lerp(startValue, endValue, lerp);
  922. int newValueInt = (int)Math.Ceiling(maxPBValue * newValue);
  923. if (this.cancelRequested)
  924. {
  925. this.progressDialog.CancelEnabled = false;
  926. this.progressDialog.Title = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Canceling");
  927. this.progressDialog.ProcessMsg = string.Empty;
  928. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
  929. }
  930. else
  931. {
  932. this.progressDialog.CancelEnabled = true;
  933. this.progressDialog.Title = this.itemName;
  934. string progressFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ProgressText.Format");
  935. string progressText = string.Format(progressFormat, this.itemOrdinal + 1, this.itemCount);
  936. this.progressDialog.ProcessMsg = progressText;
  937. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
  938. this.progressDialog.ProgressBar.Value = newValueInt;
  939. }
  940. }
  941. }
  942. public static DialogResult ChooseFiles(Control owner, out string[] fileNames, bool multiselect, string startingDir)
  943. {
  944. FileTypeCollection fileTypes = FileTypes.GetFileTypes();
  945. using (IFileOpenDialog ofd = new ClassicFileOpenDialog())
  946. {
  947. if (startingDir != null)
  948. {
  949. ofd.InitialDirectory = startingDir;
  950. }
  951. else
  952. {
  953. ofd.InitialDirectory = GetDefaultSavePath();
  954. }
  955. ofd.CheckFileExists = true;
  956. ofd.CheckPathExists = true;
  957. ofd.Multiselect = multiselect;
  958. ofd.Filter = fileTypes.ToString(true, PdnResources.GetString("FileDialog.Types.AllImages"), false, true);
  959. ofd.FilterIndex = 0;
  960. DialogResult result = ShowFileDialog(owner, ofd);
  961. if (result == DialogResult.OK)
  962. {
  963. fileNames = ofd.FileNames;
  964. }
  965. else
  966. {
  967. fileNames = new string[0];
  968. }
  969. return result;
  970. }
  971. }
  972. private static string GetDefaultSavePath()
  973. {
  974. string myPics;
  975. try
  976. {
  977. myPics = Shell.GetVirtualPath(VirtualFolderName.UserPictures, false);
  978. DirectoryInfo dirInfo = new DirectoryInfo(myPics); // validate
  979. }
  980. catch (Exception)
  981. {
  982. myPics = "";
  983. }
  984. string dir = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, null);
  985. if (dir == null)
  986. {
  987. dir = myPics;
  988. }
  989. else
  990. {
  991. try
  992. {
  993. DirectoryInfo dirInfo = new DirectoryInfo(dir);
  994. if (!dirInfo.Exists)
  995. {
  996. dir = myPics;
  997. }
  998. }
  999. catch (Exception)
  1000. {
  1001. dir = myPics;
  1002. }
  1003. }
  1004. return dir;
  1005. }
  1006. /// <summary>
  1007. /// 图片保存,保存当前激活图片,用来替换原框架的保存
  1008. /// 1)若当前打开的非硬盘打开图片,点击保存,系统打开保存路径窗口(图1)
  1009. /// 若命名在保存路径重复,则打开对应提示窗口,具体效果可点击图1中的【保存】按钮查看效果
  1010. /// 2)若硬盘图像未保存点击保存按钮,根据系统设置进行保存,写死设置为:
  1011. /// 生成配置文件、不保存网格数据、不嵌入标注及测量信息、保存后不关闭图像、不压缩图像
  1012. /// </summary>
  1013. /// <returns></returns>
  1014. public bool DoSaveNew()
  1015. {
  1016. //判断是否是从硬盘打开,以下是原来的代码,是根据文件名判断的
  1017. string newFileName;
  1018. FileType newFileType;
  1019. SaveConfigToken newSaveConfigToken;
  1020. GetDocumentSaveOptions(out newFileName, out newFileType, out newSaveConfigToken);
  1021. if (zipHandleHelper != null)
  1022. newFileName = zipHandleHelper.zipName;
  1023. // 如果没有指定文件名(不是从硬盘打开,是生成或从相机获得),则执行另存为
  1024. if (newFileName == null)
  1025. {
  1026. return DoSaveAsNew();
  1027. }
  1028. else
  1029. {
  1030. try
  1031. {
  1032. //获取文件后缀名
  1033. string extension = Path.GetExtension(newFileName);
  1034. //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像、不保存相
  1035. using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
  1036. {
  1037. //保存图片
  1038. if (!extension.Equals(".tga"))//不是压缩包
  1039. {
  1040. ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1041. if (extension.Equals(".jpg"))
  1042. {
  1043. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1044. }
  1045. else if (extension.Equals(".bmp"))
  1046. {
  1047. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
  1048. }
  1049. else if (extension.Equals("TIFF"))
  1050. {
  1051. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Tiff);
  1052. }
  1053. EncoderParameters parms = new EncoderParameters(1);
  1054. EncoderParameter parm = new EncoderParameter(Encoder.Quality, 100L);
  1055. parms.Param[0] = parm;
  1056. bitmap.Save(newFileName, icf, parms);
  1057. }
  1058. //生成配置文件
  1059. if (true)
  1060. {
  1061. //组织配置文件的数据
  1062. PicConfigModel picConfigModel = new PicConfigModel();
  1063. picConfigModel.labels = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Label);
  1064. picConfigModel.measures = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Measure);
  1065. //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
  1066. picConfigModel.hardware = new PicConfigModel.Hardware();
  1067. //picConfigModel.hardware.microscope = "显微镜";
  1068. //picConfigModel.hardware.objective = "物镜";
  1069. //picConfigModel.hardware.magnificationChanger = "变倍器";
  1070. //picConfigModel.hardware.exposureTime = "曝光时间";
  1071. //相机参数赋值
  1072. GetCameraParameters(picConfigModel);
  1073. if (!extension.Equals(".tga"))//压缩包不清楚是否要保存基础和标尺等信息
  1074. {
  1075. picConfigModel.meta = new PicConfigModel.Meta();
  1076. picConfigModel.rule = new PicConfigModel.Rule();
  1077. picConfigModel.meta.format = extension;
  1078. picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  1079. if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0))
  1080. {
  1081. picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
  1082. picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
  1083. picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
  1084. picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
  1085. picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
  1086. }
  1087. else
  1088. {
  1089. if (Startup.instance.ruleDB != null)
  1090. {
  1091. picConfigModel.rule.ruler_name = Startup.instance.ruleDB.ruler_name;
  1092. picConfigModel.rule.gain_multiple = Startup.instance.ruleDB.gain_multiple;
  1093. picConfigModel.rule.pixel_length = (int)Startup.instance.ruleDB.pixel_length;
  1094. picConfigModel.rule.physical_length = Startup.instance.ruleDB.physical_length;
  1095. picConfigModel.rule.ruler_units = Startup.instance.ruleDB.ruler_units;
  1096. }
  1097. }
  1098. FileInfo fileInfo = new FileInfo(newFileName);
  1099. long lengthOfDocument = fileInfo.Length;
  1100. picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument); ;
  1101. //获取图像所在的目录
  1102. string directoryPath = Path.GetDirectoryName(newFileName);
  1103. //获取不带后缀的文件名
  1104. string noExtension = Path.GetFileNameWithoutExtension(newFileName);
  1105. picConfigModel.meta.text = noExtension;
  1106. //按路径和名称保存xml文件
  1107. string userInfoXml = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  1108. //xml保存路径
  1109. string filePath = directoryPath + "\\" + noExtension + ".xml";
  1110. //保存xml
  1111. FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
  1112. }
  1113. else
  1114. {
  1115. if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel))
  1116. MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
  1117. }
  1118. }
  1119. this.Document.Dirty = false;
  1120. }
  1121. }
  1122. catch (Exception)
  1123. {
  1124. MessageBox.Show(PdnResources.GetString("Menu.Imagesavefailed.text"));
  1125. return false;
  1126. }
  1127. }
  1128. return true;
  1129. }
  1130. /// <summary>
  1131. /// 获取批量保存中设置的参数,按生成规律提取文件名称
  1132. /// </summary>
  1133. /// <param name="file_Name">文件名称</param>
  1134. /// <returns></returns>
  1135. public bool GetParameters(out string file_Name)
  1136. {
  1137. file_Name = string.Empty;
  1138. batchSaveAutoModel = XmlSerializeHelper.DESerializer<BatchSaveAutoModel>(FileOperationHelper.ReadStringFromFile(Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml", FileMode.Open));
  1139. if (batchSaveAutoModel.Whether)
  1140. {
  1141. file_Name = batchSaveAutoModel.prefix + batchSaveAutoModel.fileName + "_" + batchSaveAutoModel.startNum + batchSaveAutoModel.suffix;
  1142. batchSaveAutoModel.startNum = batchSaveAutoModel.startNum + 1;
  1143. //另存为XML
  1144. string stageModelXml = XmlSerializeHelper.XmlSerialize<BatchSaveAutoModel>(batchSaveAutoModel);
  1145. string filePath = Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml";
  1146. FileOperationHelper.WriteStringToFile(stageModelXml, filePath, FileMode.Create);
  1147. }
  1148. return batchSaveAutoModel.Whether;
  1149. }
  1150. /// <summary>
  1151. /// 文件另存,用来替换原框架的保存
  1152. /// 1)将图片另存到其他位置,即变化不保存在原图像上
  1153. /// 2)点击另存为,打开保存路径窗口(图1)
  1154. /// 3)并根据(图1)中对应的设置判断是否关闭打开的图像
  1155. /// 4)若名称重复,则弹出对应提示,查看效果可点击图1中的【保存】按钮
  1156. /// </summary>
  1157. /// <returns></returns>
  1158. public bool DoSaveAsNew(int mode = 0)
  1159. {
  1160. //获取批量保存中设置的参数,提取文件名称
  1161. string file_Name;
  1162. //判断是否是压缩包文件
  1163. bool isZipFile = false;
  1164. if (zipHandleHelper != null)
  1165. isZipFile = true;
  1166. using (SaveFileDialog saveDialog = new SaveFileDialog())
  1167. {
  1168. ConfigModel configModel = Startup.instance.configModel;//获取另存窗口几个选项的配置
  1169. File.MySaveDialogControl saveDialogCtrl = new File.MySaveDialogControl(@"C:\Users\dlrj\Desktop\晶粒度-冷轧薄板晶粒度评级2 - 副本.JPG"/*lblFilePath.Text*/, this);
  1170. //saveDialogCtrl.FileDlgInitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
  1171. saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
  1172. //生成配置文件选中状态
  1173. if (configModel.WhetherGenerateConfig == 0)
  1174. saveDialogCtrl.checkBox1.Checked = false;
  1175. //关闭图像选中状态
  1176. if (configModel.WhetherCloseAfterSave == 0)
  1177. saveDialogCtrl.checkBox2.Checked = false;
  1178. if (isZipFile)
  1179. {
  1180. saveDialog.Filter = "Tga(*.tga)|*.tga";
  1181. saveDialog.DefaultExt = "tga";
  1182. saveDialogCtrl.checkBox3.Visible = false;
  1183. saveDialogCtrl.checkBox4.Visible = false;
  1184. saveDialogCtrl.checkBox5.Visible = false;
  1185. saveDialogCtrl.checkBox6.Visible = false;
  1186. saveDialogCtrl.numericUpDown1.Visible = false;
  1187. saveDialogCtrl.label1.Visible = false;
  1188. }
  1189. else
  1190. {
  1191. if (mode > 0)
  1192. {
  1193. saveDialogCtrl.checkBox2.Checked = false;
  1194. saveDialogCtrl.checkBox2.Enabled = false;
  1195. saveDialogCtrl.checkBox6.Enabled = false;
  1196. }
  1197. //保存网格选中状态
  1198. if (configModel.WhetherSaveGridData == 1)
  1199. saveDialogCtrl.checkBox3.Checked = true;
  1200. //标注测量嵌入图像选中状态
  1201. if (configModel.WhetherLabelMeasureInsert == 1)
  1202. saveDialogCtrl.checkBox4.Checked = true;
  1203. if (configModel.PhaseInsert == 1)
  1204. saveDialogCtrl.checkBox6.Checked = true;
  1205. //压缩比例选中状态
  1206. if (configModel.WhetherCompression == 1)
  1207. saveDialogCtrl.checkBox5.Checked = true;
  1208. saveDialogCtrl.numericUpDown1.Value = configModel.CompressionRatio;//压缩比例数值
  1209. saveDialog.Filter = "Jpeg(*.jpg)|*.jpg|Tiff(*.tiff)|*.tiff|Bmp(*.bmp)|*.bmp";
  1210. saveDialog.DefaultExt = "jpg";
  1211. }
  1212. saveDialog.FilterIndex = 1;
  1213. saveDialog.CheckFileExists = false;// true;
  1214. saveDialog.AddExtension = true;
  1215. string friendName = this.GetFriendlyName();
  1216. string m_FileName = Path.GetFileNameWithoutExtension(friendName);//friendName.Substring(friendName.LastIndexOf('\\') + 1, friendName.LastIndexOf('.') - friendName.LastIndexOf('\\') - 1);
  1217. string suffixName = Path.GetExtension(friendName);//friendName.Substring(friendName.LastIndexOf(".") + 1, (friendName.Length - friendName.LastIndexOf(".") - 1)); ;
  1218. //判断是否有保存参数,有则获取,无则使用原始文件名
  1219. if (GetParameters(out file_Name))
  1220. {
  1221. saveDialog.FileName = file_Name;
  1222. }
  1223. else
  1224. {
  1225. if (mode > 0)
  1226. {
  1227. saveDialog.FileName = m_FileName /*+ " - " + PdnResources.GetString("Menu.Acopyofth.Text") */+ suffixName;
  1228. }
  1229. else
  1230. {
  1231. saveDialog.FileName = m_FileName + " - " + PdnResources.GetString("Menu.Acopyofth.Text") + suffixName;
  1232. }
  1233. }
  1234. saveDialog.DereferenceLinks = true;
  1235. //saveDialog.ShowHelp = true;
  1236. if (Environment.OSVersion.Version.Major < 6)
  1237. saveDialog.SetPlaces(new object[] { (int)Places.Desktop, (int)Places.Printers, (int)Places.Favorites, (int)Places.Programs, (int)Places.Fonts, });
  1238. string path = "";
  1239. if (saveDialog.ShowDialog(saveDialogCtrl, this) == DialogResult.OK)
  1240. {
  1241. //文件路径
  1242. path = saveDialog.FileName;
  1243. string fileText = string.Empty;
  1244. if (path.Contains("\\"))
  1245. {
  1246. int index = path.LastIndexOf('\\');
  1247. fileText = path.Substring(0, index);
  1248. }
  1249. this.fileText = fileText;
  1250. this.filePath = saveDialog.FileName;
  1251. //是否生成配置文件
  1252. bool createConfig = saveDialogCtrl.checkBox1.Checked;
  1253. //保存后是否关闭图像
  1254. bool afterSaveClost = saveDialogCtrl.checkBox2.Checked;
  1255. //保存时是否保存网格数据
  1256. bool saveGridLine = saveDialogCtrl.checkBox3.Checked;
  1257. //标注及测量信息是否嵌入图像
  1258. bool implantLabelAndMeasure = saveDialogCtrl.checkBox4.Checked;
  1259. //相信息是否嵌入图像
  1260. bool implantPhase = saveDialogCtrl.checkBox6.Checked;
  1261. //是否压缩
  1262. bool compress = saveDialogCtrl.checkBox5.Checked;
  1263. //压缩比例
  1264. decimal compressRate = saveDialogCtrl.numericUpDown1.Value;
  1265. //重新保存选项到配置文件
  1266. if (createConfig)
  1267. configModel.WhetherGenerateConfig = 1;
  1268. else
  1269. configModel.WhetherGenerateConfig = 0;
  1270. if (afterSaveClost)
  1271. configModel.WhetherCloseAfterSave = 1;
  1272. else
  1273. configModel.WhetherCloseAfterSave = 0;
  1274. if (saveGridLine)
  1275. configModel.WhetherSaveGridData = 1;
  1276. else
  1277. configModel.WhetherSaveGridData = 0;
  1278. if (implantLabelAndMeasure)
  1279. configModel.WhetherLabelMeasureInsert = 1;
  1280. else
  1281. configModel.WhetherLabelMeasureInsert = 0;
  1282. if (implantPhase)
  1283. configModel.PhaseInsert = 1;
  1284. else
  1285. configModel.PhaseInsert = 0;
  1286. if (compress)
  1287. configModel.WhetherCompression = 1;
  1288. else
  1289. configModel.WhetherCompression = 0;
  1290. configModel.CompressionRatio = compressRate;
  1291. string configModelXml = XmlSerializeHelper.XmlSerialize<ConfigModel>(configModel);
  1292. FileOperationHelper.WriteStringToFile(configModelXml, Application.StartupPath + "\\Config\\" +
  1293. Startup.instance.SettingPrefix + "\\Config.xml", FileMode.Create);
  1294. //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像
  1295. using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
  1296. {
  1297. //获取文件后缀名
  1298. string extension = Path.GetExtension(path);
  1299. if (!extension.Equals(".tga"))
  1300. {
  1301. using (Bitmap dstBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat))
  1302. {
  1303. Graphics graphics = Graphics.FromImage(dstBitmap);
  1304. //判断保存时是否保存相信息
  1305. if (implantPhase)
  1306. {
  1307. if (this.phaseModels != null && this.phaseModels.Count > 0)
  1308. {
  1309. foreach (PhaseModel model in this.phaseModels)
  1310. {
  1311. if (model.choise)
  1312. {
  1313. graphics.DrawImage(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(model.mat), 0, 0, bitmap.Width, bitmap.Height);
  1314. }
  1315. }
  1316. }
  1317. }
  1318. //判断保存时是否保存网格数据,是则嵌入图像
  1319. if (saveGridLine)
  1320. {
  1321. DrawRulerHelper.drawGrid(AppWorkspace.GetGridModel(), graphics, this.CompositionSurface.Width, this.CompositionSurface.Height);
  1322. }
  1323. //判断标注及测量信息是否嵌入图像
  1324. //this.SurfaceBox.Surface.CreateAliasedBitmapWithLayer(true, true);
  1325. if (implantLabelAndMeasure)
  1326. {
  1327. if (this.GraphicsList != null && this.GraphicsList.Count > 0)
  1328. {
  1329. GraphicsList.UnselectAll();
  1330. this.GraphicsList.Draw(graphics);
  1331. }
  1332. }
  1333. //保存图片
  1334. ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1335. if (extension.Equals(".jpg"))
  1336. {
  1337. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1338. }
  1339. else if (extension.Equals(".bmp"))
  1340. {
  1341. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
  1342. }
  1343. else if (extension.Equals(".tiff"))
  1344. {
  1345. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Tiff);
  1346. }
  1347. EncoderParameters parms = new EncoderParameters(1);
  1348. EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L);
  1349. parms.Param[0] = parm;
  1350. dstBitmap.Save(path, icf, parms);
  1351. }
  1352. }
  1353. else
  1354. {
  1355. //另存的路径与原zip路径不相同,则copy一份;相同不做处理
  1356. if (!path.Equals(zipHandleHelper.zipName))
  1357. {
  1358. System.IO.File.Copy(zipHandleHelper.zipName, path, true);
  1359. }
  1360. }
  1361. //保存配置文件
  1362. if (createConfig)
  1363. {
  1364. //组织配置文件的数据
  1365. PicConfigModel picConfigModel = new PicConfigModel();
  1366. if (!implantLabelAndMeasure) picConfigModel.labels = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Label);
  1367. if (!implantLabelAndMeasure) picConfigModel.measures = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Measure);
  1368. //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
  1369. picConfigModel.hardware = new PicConfigModel.Hardware();
  1370. //相机参数赋值
  1371. GetCameraParameters(picConfigModel);
  1372. picConfigModel.meta = new PicConfigModel.Meta();
  1373. picConfigModel.rule = new PicConfigModel.Rule();
  1374. picConfigModel.meta.format = extension;
  1375. picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  1376. if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0))
  1377. {
  1378. picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
  1379. picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
  1380. picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
  1381. picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
  1382. picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
  1383. }
  1384. else
  1385. {
  1386. if (Startup.instance.ruleDB != null)
  1387. {
  1388. picConfigModel.rule.ruler_name = Startup.instance.ruleDB.ruler_name;
  1389. picConfigModel.rule.gain_multiple = Startup.instance.ruleDB.gain_multiple;
  1390. picConfigModel.rule.pixel_length = (int)Startup.instance.ruleDB.pixel_length;
  1391. picConfigModel.rule.physical_length = Startup.instance.ruleDB.physical_length;
  1392. picConfigModel.rule.ruler_units = Startup.instance.ruleDB.ruler_units;
  1393. }
  1394. }
  1395. FileInfo fileInfo = new FileInfo(path);
  1396. long lengthOfDocument = fileInfo.Length;
  1397. picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument);
  1398. //获取图像所在的目录
  1399. string directoryPath = Path.GetDirectoryName(path);
  1400. //获取不带后缀的文件名
  1401. string noExtension = Path.GetFileNameWithoutExtension(path);
  1402. picConfigModel.meta.text = noExtension;
  1403. //按路径和名称保存xml文件
  1404. string userInfoXml = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  1405. //xml保存路径
  1406. string filePath = directoryPath + "\\" + noExtension + ".xml";
  1407. //保存xml
  1408. FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
  1409. if (extension.Equals(".tga"))
  1410. {
  1411. //copy了新的zip包,则修改新zip包内的xml
  1412. if (!path.Equals(zipHandleHelper.zipName))
  1413. {
  1414. ZipHandleHelper newZipFile = new ZipHandleHelper(path);
  1415. if (newZipFile != null)
  1416. {
  1417. if (!newZipFile.ModifyLabelAndMeasureXml(picConfigModel))
  1418. MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
  1419. }
  1420. }
  1421. //没有copy,修改旧zip包的xml
  1422. else
  1423. {
  1424. if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel))
  1425. MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
  1426. }
  1427. }
  1428. }
  1429. if (this.Document != null)
  1430. {
  1431. this.Document.Dirty = false;
  1432. }
  1433. if (mode == 0)
  1434. {
  1435. //保存后是否关闭图像
  1436. if (afterSaveClost)
  1437. {
  1438. this.AppWorkspace.PerformAction(new CloseWorkspaceAction());
  1439. }
  1440. else
  1441. {
  1442. this.filePath = path;
  1443. this.fileText = this.GetFriendlyName();
  1444. this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this);
  1445. }
  1446. }
  1447. }
  1448. }
  1449. else
  1450. {
  1451. return false;
  1452. }
  1453. }
  1454. return true;
  1455. }
  1456. /// <summary>
  1457. /// 相机参数赋值
  1458. /// </summary>
  1459. /// <param name="picConfigModel">图片对应的XML配置</param>
  1460. public void GetCameraParameters(PicConfigModel picConfigModel)
  1461. {
  1462. if (this.hardware != null)
  1463. {
  1464. picConfigModel.hardware.microscope = this.hardware.microscope;
  1465. picConfigModel.hardware.objective = this.hardware.objective;
  1466. picConfigModel.hardware.magnificationChanger = this.hardware.magnificationChanger;
  1467. picConfigModel.hardware.exposureTime = this.hardware.cameraParamModel.parame.LNExposure.ToString();
  1468. picConfigModel.hardware.Resolution = this.hardware.cameraParamModel.parame.Resolution;
  1469. picConfigModel.hardware.GlobalGain = this.hardware.cameraParamModel.parame.GlobalGain;
  1470. picConfigModel.hardware.Brightness = this.hardware.cameraParamModel.parame.Brightness;
  1471. picConfigModel.hardware.ATExposure = this.hardware.cameraParamModel.parame.ATExposure;
  1472. picConfigModel.hardware.PreExposure = this.hardware.cameraParamModel.parame.PreExposure;
  1473. picConfigModel.hardware.WhiteBalance = this.hardware.cameraParamModel.parame.WhiteBalance;
  1474. picConfigModel.hardware.BlackBalance = this.hardware.cameraParamModel.parame.BlackBalance;
  1475. picConfigModel.hardware.PreExposure = this.hardware.cameraParamModel.parame.PreExposure;
  1476. picConfigModel.hardware.Monochromatic = this.hardware.cameraParamModel.parame.Monochromatic;
  1477. picConfigModel.hardware.FlatFieldCorrection = this.hardware.cameraParamModel.parame.FlatFieldCorrection;
  1478. picConfigModel.hardware.Sharpness = this.hardware.cameraParamModel.parame.Sharpness;
  1479. picConfigModel.hardware.HDR = this.hardware.cameraParamModel.parame.HDR;
  1480. picConfigModel.hardware.AreaWhiteBalanceEnable = this.hardware.cameraParamModel.parame.AreaWhiteBalanceEnable;
  1481. picConfigModel.hardware.Gamma = this.hardware.cameraParamModel.parame.Gamma;
  1482. picConfigModel.hardware.Contrast = this.hardware.cameraParamModel.parame.Contrast;
  1483. picConfigModel.hardware.Saturation = this.hardware.cameraParamModel.parame.Saturation;
  1484. picConfigModel.hardware.RedChannel = this.hardware.cameraParamModel.parame.RedChannel;
  1485. picConfigModel.hardware.GreenChannel = this.hardware.cameraParamModel.parame.GreenChannel;
  1486. picConfigModel.hardware.BlueChannel = this.hardware.cameraParamModel.parame.BlueChannel;
  1487. picConfigModel.hardware.ColorTemperature = this.hardware.cameraParamModel.parame.ColorTemperature;
  1488. picConfigModel.hardware.Horizontal = this.hardware.cameraParamModel.parame.Horizontal;
  1489. picConfigModel.hardware.Vertical = this.hardware.cameraParamModel.parame.Vertical;
  1490. picConfigModel.hardware.VerticalCorrection = this.hardware.cameraParamModel.parame.VerticalCorrection;
  1491. picConfigModel.hardware.ChannelsSelect = this.hardware.cameraParamModel.parame.ChannelsSelect;
  1492. picConfigModel.hardware.RotateR90 = this.hardware.cameraParamModel.parame.RotateR90;
  1493. picConfigModel.hardware.RotateL90 = this.hardware.cameraParamModel.parame.RotateL90;
  1494. picConfigModel.hardware.Rotate = this.hardware.cameraParamModel.parame.Rotate;
  1495. picConfigModel.hardware.Hue = this.hardware.cameraParamModel.parame.Hue;
  1496. }
  1497. }
  1498. /// <summary>
  1499. /// 批量保存
  1500. /// </summary>
  1501. /// <param name="fileName">文件名</param>
  1502. /// <param name="createConfig">是否生成配置文件</param>
  1503. /// <param name="afterSaveClost">保存后是否关闭图像</param>
  1504. /// <param name="saveGridLine">保存时是否保存网格数据</param>
  1505. /// <param name="implantLabelAndMeasure">标注及测量信息是否嵌入图像</param>
  1506. /// <param name="compress">是否压缩</param>
  1507. /// <param name="compressRate">压缩比例</param>
  1508. /// <returns></returns>
  1509. public bool SaveForBatch(string fileName, bool createConfig, bool afterSaveClost, bool saveGridLine, bool implantLabelAndMeasure, bool compress, decimal compressRate, bool implantPhase)
  1510. {
  1511. //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像
  1512. using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
  1513. {
  1514. Graphics graphics = Graphics.FromImage(bitmap);
  1515. if (implantPhase)
  1516. {
  1517. if (this.phaseModels != null && this.phaseModels.Count > 0)
  1518. {
  1519. foreach (PhaseModel model in this.phaseModels)
  1520. {
  1521. if (model.choise)
  1522. {
  1523. graphics.DrawImage(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(model.mat), 0, 0, bitmap.Width, bitmap.Height);
  1524. }
  1525. }
  1526. }
  1527. }
  1528. //判断保存时是否保存网格数据,是则嵌入图像
  1529. if (saveGridLine)
  1530. {
  1531. DrawRulerHelper.drawGrid(AppWorkspace.GetGridModel(), graphics, this.CompositionSurface.Width, this.CompositionSurface.Height);
  1532. }
  1533. //判断标注及测量信息是否嵌入图像
  1534. //this.SurfaceBox.Surface.CreateAliasedBitmapWithLayer(true, true);
  1535. if (implantLabelAndMeasure)
  1536. {
  1537. if (this.GraphicsList != null && this.GraphicsList.Count > 0)
  1538. {
  1539. this.GraphicsList.Draw(graphics);
  1540. }
  1541. }
  1542. //获取文件后缀名
  1543. string extension = Path.GetExtension(fileName);
  1544. //保存图片
  1545. ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1546. if (extension.Equals(".jpg"))
  1547. {
  1548. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1549. }
  1550. else if (extension.Equals(".bmp"))
  1551. {
  1552. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
  1553. }
  1554. else if (extension.Equals(".tiff"))
  1555. {
  1556. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Tiff);
  1557. }
  1558. EncoderParameters parms = new EncoderParameters(1);
  1559. EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L);
  1560. parms.Param[0] = parm;
  1561. bitmap.Save(fileName, icf, parms);
  1562. //保存配置文件
  1563. if (createConfig)
  1564. {
  1565. //组织配置文件的数据
  1566. PicConfigModel picConfigModel = new PicConfigModel();
  1567. picConfigModel.hardware = new PicConfigModel.Hardware();
  1568. if (!implantLabelAndMeasure) picConfigModel.labels = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Label);
  1569. if (!implantLabelAndMeasure) picConfigModel.measures = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Measure);
  1570. //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
  1571. picConfigModel.meta = new PicConfigModel.Meta();
  1572. picConfigModel.rule = new PicConfigModel.Rule();
  1573. picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
  1574. picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
  1575. picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
  1576. picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
  1577. picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
  1578. GetCameraParameters(picConfigModel);
  1579. //获取图像所在的目录
  1580. string directoryPath = Path.GetDirectoryName(fileName);
  1581. //获取不带后缀的文件名
  1582. string noExtension = Path.GetFileNameWithoutExtension(fileName);
  1583. //按路径和名称保存xml文件
  1584. string userInfoXml = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  1585. //xml保存路径
  1586. string filePath = directoryPath + "\\" + noExtension + ".xml";
  1587. //保存xml
  1588. FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
  1589. }
  1590. if (this.Document != null)
  1591. {
  1592. this.Document.Dirty = false;
  1593. }
  1594. //保存后是否关闭图像
  1595. if (afterSaveClost)
  1596. {
  1597. this.Document.Dirty = false;
  1598. this.AppWorkspace.toRemoveDocumentWorkspaceIndex = this.AppWorkspace.DocumentWorkspaces.Length - 1;
  1599. this.AppWorkspace.PerformAction(new CloseWorkspaceAction());
  1600. }
  1601. else
  1602. {
  1603. this.filePath = fileName;
  1604. this.fileText = this.GetFriendlyName();
  1605. this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this);
  1606. }
  1607. }
  1608. return true;
  1609. }
  1610. public static Document LoadDocument(Control owner, string fileName, out FileType fileTypeResult, ProgressEventHandler progressCallback)
  1611. {
  1612. FileTypeCollection fileTypes;
  1613. int ftIndex;
  1614. FileType fileType;
  1615. fileTypeResult = null;
  1616. try
  1617. {
  1618. fileTypes = FileTypes.GetFileTypes();
  1619. ftIndex = fileTypes.IndexOfExtension(Path.GetExtension(fileName));
  1620. if (ftIndex == -1)
  1621. {
  1622. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ImageTypeNotRecognized"));
  1623. return null;
  1624. }
  1625. fileType = fileTypes[ftIndex];
  1626. fileTypeResult = fileType;
  1627. }
  1628. catch (ArgumentException)
  1629. {
  1630. string format = PdnResources.GetString("LoadImage.Error.InvalidFileName.Format");
  1631. string error = string.Format(format, fileName);
  1632. Utility.ErrorBox(owner, error);
  1633. return null;
  1634. }
  1635. Document document = null;
  1636. using (new WaitCursorChanger(owner))
  1637. {
  1638. Utility.GCFullCollect();
  1639. Stream stream = null;
  1640. OpenCvSharp.Mat tempMat = null;
  1641. try
  1642. {
  1643. try
  1644. {
  1645. tempMat = new Mat(fileName);
  1646. stream = tempMat.ToMemoryStream(Path.GetExtension(fileName));
  1647. //stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  1648. long totalBytes = 0;
  1649. SiphonStream siphonStream = new SiphonStream(stream);
  1650. IOEventHandler ioEventHandler = null;
  1651. ioEventHandler =
  1652. delegate (object sender, IOEventArgs e)
  1653. {
  1654. if (progressCallback != null)
  1655. {
  1656. totalBytes += (long)e.Count;
  1657. double percent = Utility.Clamp(100.0 * ((double)totalBytes / (double)siphonStream.Length), 0, 100);
  1658. progressCallback(null, new ProgressEventArgs(percent));
  1659. }
  1660. };
  1661. siphonStream.IOFinished += ioEventHandler;
  1662. using (new WaitCursorChanger(owner))
  1663. {
  1664. document = fileType.Load(siphonStream);
  1665. if (progressCallback != null)
  1666. {
  1667. progressCallback(null, new ProgressEventArgs(100.0));
  1668. }
  1669. }
  1670. siphonStream.IOFinished -= ioEventHandler;
  1671. siphonStream.Close();
  1672. GC.Collect();
  1673. }
  1674. catch (WorkerThreadException ex)
  1675. {
  1676. Type innerExType = ex.InnerException.GetType();
  1677. ConstructorInfo ci = innerExType.GetConstructor(new Type[] { typeof(string), typeof(Exception) });
  1678. if (ci == null)
  1679. {
  1680. throw;
  1681. }
  1682. else
  1683. {
  1684. Exception ex2 = (Exception)ci.Invoke(new object[] { "Worker thread threw an exception of this type", ex.InnerException });
  1685. throw ex2;
  1686. }
  1687. }
  1688. }
  1689. catch (ArgumentException)
  1690. {
  1691. if (fileName.Length == 0)
  1692. {
  1693. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.BlankFileName"));
  1694. }
  1695. else
  1696. {
  1697. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ArgumentException"));
  1698. }
  1699. }
  1700. catch (UnauthorizedAccessException)
  1701. {
  1702. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.UnauthorizedAccessException"));
  1703. }
  1704. catch (SecurityException)
  1705. {
  1706. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SecurityException"));
  1707. }
  1708. catch (FileNotFoundException)
  1709. {
  1710. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.FileNotFoundException"));
  1711. }
  1712. catch (DirectoryNotFoundException)
  1713. {
  1714. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.DirectoryNotFoundException"));
  1715. }
  1716. catch (PathTooLongException)
  1717. {
  1718. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.PathTooLongException"));
  1719. }
  1720. catch (IOException)
  1721. {
  1722. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.IOException"));
  1723. }
  1724. catch (SerializationException)
  1725. {
  1726. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SerializationException"));
  1727. }
  1728. catch (OutOfMemoryException)
  1729. {
  1730. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.OutOfMemoryException"));
  1731. }
  1732. catch (Exception)
  1733. {
  1734. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.Exception"));
  1735. }
  1736. finally
  1737. {
  1738. if (stream != null)
  1739. {
  1740. stream.Close();
  1741. stream = null;
  1742. }
  1743. if (tempMat != null)
  1744. {
  1745. tempMat.Dispose();
  1746. tempMat = null;
  1747. }
  1748. }
  1749. }
  1750. return document;
  1751. }
  1752. /// <summary>
  1753. /// 更新测量单位,刷新UI
  1754. /// </summary>
  1755. /// <param name="measurementUnit"></param>
  1756. public void UpdateMeasureUnit(MeasurementUnit measurementUnit)
  1757. {
  1758. //循环所有测量,更新单位
  1759. if (this.GraphicsList != null
  1760. && this.GraphicsList.Count > 0)
  1761. {
  1762. int count = this.GraphicsList.Count;
  1763. for (int i = 0; i < count; i++)
  1764. {
  1765. if (this.GraphicsList[i].objectType == DrawClass.Measure)
  1766. {
  1767. ((MeasureDrawObject)(this.GraphicsList[i])).MeasurementUnit = measurementUnit;
  1768. }
  1769. if (this.GraphicsList[i].objectType == DrawClass.Label)
  1770. {
  1771. }
  1772. }
  1773. }
  1774. this.Refresh();
  1775. }
  1776. public override void ToolStripMenuItem1_Click(object sender, EventArgs e)
  1777. {
  1778. using (MeasureSettingDialog af = new MeasureSettingDialog(AppWorkspace))
  1779. {
  1780. af.StartPosition = FormStartPosition.CenterScreen;
  1781. af.ShowDialog();
  1782. }
  1783. }
  1784. public override void ToolStripMenuItem2_Click(object sender, EventArgs e)
  1785. {
  1786. using (LabelSettingDialog af = new LabelSettingDialog(AppWorkspace))
  1787. {
  1788. af.StartPosition = FormStartPosition.CenterScreen;
  1789. af.ShowDialog();
  1790. }
  1791. }
  1792. public override void ToolStripMenuItem3_Click(object sender, EventArgs e)
  1793. {
  1794. //using (MeasureListSetDialog dialog = new MeasureListSetDialog(this.appWorkspace, MeasureListDialog.drawNodes
  1795. // , MeasureListDialog.dataNodes, MeasureListDialog.allDrawNodes, MeasureListDialog.allDataNodes))
  1796. //{
  1797. // dialog.StartPosition = FormStartPosition.CenterParent;
  1798. // dialog.ShowDialog();
  1799. //}
  1800. for (int i = 0; i < this.GraphicsList.Count; i++)
  1801. {
  1802. if (GraphicsList[i].Selected)
  1803. {
  1804. MeasurementPropertiesDialog measurementPropertiesDialog = new MeasurementPropertiesDialog(this.appWorkspace, this.GraphicsList[i]);
  1805. measurementPropertiesDialog.StartPosition = FormStartPosition.CenterScreen;
  1806. measurementPropertiesDialog.ShowDialog();
  1807. }
  1808. }
  1809. }
  1810. public override void ToolStripMenuItem4_Click(object sender, EventArgs e)
  1811. {
  1812. for (int i = 0; i < this.GraphicsList.Count; i++)
  1813. {
  1814. if (this.GraphicsList[i].Selected)
  1815. {
  1816. //判断如果是水印
  1817. if (this.GraphicsList[i].drawToolType == DrawToolType.DrawWaterMark)
  1818. {
  1819. LabelWaterMarkStyleDialog labelWaterMarkStyleDialog = new LabelWaterMarkStyleDialog(this.appWorkspace, this.GraphicsList[i]);
  1820. labelWaterMarkStyleDialog.StartPosition = FormStartPosition.CenterScreen;
  1821. labelWaterMarkStyleDialog.ShowDialog();
  1822. }
  1823. //判断如果是工字线
  1824. else if (this.GraphicsList[i].drawToolType == DrawToolType.DrawWorkType)
  1825. {
  1826. LabelWorkTypeStyleDialog labelWorkTypeStyleDialog = new LabelWorkTypeStyleDialog(this.appWorkspace, this.GraphicsList[i]);
  1827. labelWorkTypeStyleDialog.StartPosition = FormStartPosition.CenterScreen;
  1828. labelWorkTypeStyleDialog.ShowDialog();
  1829. }
  1830. //如果是标尺
  1831. else if (this.GraphicsList[i].drawToolType == DrawToolType.DrawAutoRuler || this.GraphicsList[i].drawToolType ==
  1832. DrawToolType.DrawHandModeRuler || this.GraphicsList[i].drawToolType == DrawToolType.DrawPrestoredRuler)
  1833. {
  1834. LabelRulerStyleDialog labelRulerStyleDialog = new LabelRulerStyleDialog(this.appWorkspace, this.GraphicsList[i]);
  1835. labelRulerStyleDialog.StartPosition = FormStartPosition.CenterParent;
  1836. labelRulerStyleDialog.ShowDialog();
  1837. }
  1838. //如果是其它
  1839. else
  1840. {
  1841. LabelStyleChangeDialog labelStyleChangeDialog = new LabelStyleChangeDialog(this.appWorkspace, this.GraphicsList[i]);
  1842. labelStyleChangeDialog.StartPosition = FormStartPosition.CenterScreen;
  1843. labelStyleChangeDialog.ShowDialog();
  1844. }
  1845. }
  1846. }
  1847. }
  1848. }
  1849. }