DocumentWorkspace.cs 88 KB

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