ShowVisionRender.xaml.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. using Cognex.VisionPro;
  2. using Cognex.VisionPro.ImageFile;
  3. using Prism.Events;
  4. using Prism.Ioc;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Forms.Integration;
  14. using TeamAAS_VP.Core;
  15. using TeamAAS_VP.Enums;
  16. using TeamAAS_VP.Events;
  17. using TeamAAS_VP.Interfaces;
  18. using TeamAAS_VP.Models;
  19. using TeamAAS_VP.Resources.Languages;
  20. using TeamAAS_VP.ViewModels.Home;
  21. namespace TeamAAS_VP.Views.Home
  22. {
  23. /// <summary>
  24. /// Interaction logic for ShowVisionRender
  25. /// </summary>
  26. public partial class ShowVisionRender : UserControl
  27. {
  28. private ShowVisionRenderViewModel viewModel;
  29. // key=ShowRender.Id
  30. private readonly Dictionary<Guid, WindowsFormsHost> vmRenders;
  31. private readonly Dictionary<Guid, TextBlock> Titles;
  32. private readonly IEventAggregator _eventAggregator;
  33. private readonly ISystemDatabaseService _systemDatabaseService;
  34. private readonly IProductService _productService;
  35. // ======================= 【新增】保存任务控制:防闪退/防资源泄露 =======================
  36. private CancellationTokenSource _saveImageCts = new CancellationTokenSource();
  37. private readonly SemaphoreSlim _saveSemaphore = new SemaphoreSlim(2, 2);
  38. public ShowVisionRender()
  39. {
  40. InitializeComponent();
  41. vmRenders = new Dictionary<Guid, WindowsFormsHost>();
  42. Titles = new Dictionary<Guid, TextBlock>();
  43. viewModel = DataContext as ShowVisionRenderViewModel;
  44. _eventAggregator = viewModel._eventAggregator;
  45. _systemDatabaseService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<ISystemDatabaseService>();
  46. _productService = ((Prism.PrismApplicationBase)App.Current).Container.Resolve<IProductService>();
  47. viewModel.UpdateLayout += ViewModel_UpdateLayout;
  48. _eventAggregator.GetEvent<RenderUpdateNotification>().Subscribe(UpdateRenderModuleSource);
  49. _eventAggregator.GetEvent<ProductChangedNotification>().Subscribe(ProductChanged);
  50. // 【可选】控件卸载时取消所有保存任务,避免页面关闭后仍在截图/保存导致闪退
  51. this.Unloaded += ShowVisionRender_Unloaded;
  52. }
  53. private void ShowVisionRender_Unloaded(object sender, RoutedEventArgs e)
  54. {
  55. try
  56. {
  57. _saveImageCts.Cancel();
  58. _saveImageCts.Dispose();
  59. }
  60. catch { }
  61. }
  62. /// <summary>
  63. /// 更新某个工位/模块的显示内容(图像/图形/Record/保存)
  64. /// </summary>
  65. private void UpdateRenderModuleSource(ShowRender render)
  66. {
  67. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  68. {
  69. foreach (var item in vmRenders)
  70. {
  71. if (item.Value?.Child is CogRecordDisplay disp)
  72. {
  73. ((Cognex.VisionPro.CogRecordDisplay)item.Value.Child).Record = null;
  74. ((Cognex.VisionPro.CogRecordDisplay)item.Value.Child).Image = render.Image;
  75. ((Cognex.VisionPro.CogRecordDisplay)item.Value.Child).StaticGraphics.Clear();
  76. if (render.Graphic!=null)
  77. ((Cognex.VisionPro.CogRecordDisplay)item.Value.Child).StaticGraphics.AddList(render.Graphic, "");
  78. if (render.Record != null)
  79. ((Cognex.VisionPro.CogRecordDisplay)item.Value.Child).Record = render.Record;
  80. if (render.IsSaveImage)
  81. {
  82. SaveImage(render.SaveImageModel, render.SaveImagePathModel, render.SavePath, render.Image, (Bitmap)((Cognex.VisionPro.CogRecordDisplay)item.Value.Child).CreateContentBitmap(Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom), render.Result, render.IsCompress, render.ImgPara);
  83. }
  84. break;
  85. }
  86. }
  87. /*
  88. foreach (var item in gridRender.Children)
  89. {
  90. if (item is WindowsFormsHost && ((WindowsFormsHost)item).Child is Cognex.VisionPro.CogRecordDisplay)
  91. {
  92. if (((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).Tag != null && ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).Tag.ToString() == render.CameraName)
  93. {
  94. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).Image = render.Image;
  95. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).StaticGraphics.Clear();
  96. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).StaticGraphics.AddList(render.Graphic, "");
  97. if (render.Record != null)
  98. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).Record = render.Record;
  99. if (render.IsSaveImage)
  100. {
  101. SaveImage(render.SaveImageModel, render.SaveImagePathModel, render.SavePath, render.Image, (Bitmap)((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).CreateContentBitmap(Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom), render.Result, render.IsCompress);
  102. }
  103. break;
  104. }
  105. }
  106. else if (item is Grid)
  107. {
  108. foreach (var item1 in ((Grid)item).Children)
  109. {
  110. if (item1 is WindowsFormsHost && ((WindowsFormsHost)item1).Child is Cognex.VisionPro.CogRecordDisplay)
  111. {
  112. if (((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item1).Child).Tag != null && ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item1).Child).Tag.ToString() == render.CameraName)
  113. {
  114. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item1).Child).Image = render.Image;
  115. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item1).Child).StaticGraphics.Clear();
  116. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item1).Child).StaticGraphics.AddList(render.Graphic, "");
  117. if (render.Record != null)
  118. ((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).Record = render.Record;
  119. if (render.IsSaveImage)
  120. {
  121. SaveImage(render.SaveImageModel, render.SaveImagePathModel, render.SavePath, render.Image, (Bitmap)((Cognex.VisionPro.CogRecordDisplay)((WindowsFormsHost)item).Child).CreateContentBitmap(Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom), render.Result, render.IsCompress);
  122. }
  123. break;
  124. }
  125. }
  126. }
  127. break;
  128. }
  129. }*/
  130. }));
  131. }
  132. /// <summary>
  133. /// 【核心】根据 obj.Count 自动生成 1~16 个显示格子(标题+CogRecordDisplay)
  134. /// </summary>
  135. private async void ViewModel_UpdateLayout(System.Collections.ObjectModel.ObservableCollection<Models.ShowRender> obj)
  136. {
  137. // ======================= 【关键优化】布局刷新前先取消旧保存任务 =======================
  138. try
  139. {
  140. _saveImageCts.Cancel();
  141. _saveImageCts.Dispose();
  142. }
  143. catch { }
  144. _saveImageCts = new CancellationTokenSource();
  145. System.Windows.Media.FontFamily font = Application.Current.Resources["DefaultFont"] as System.Windows.Media.FontFamily;
  146. // 1) 清理旧控件
  147. if (vmRenders.Count > 0)
  148. {
  149. foreach (var render in vmRenders)
  150. {
  151. // WindowsFormsHost.Dispose() 会销毁 WinForms 句柄,防止资源泄漏
  152. render.Value?.Dispose();
  153. }
  154. }
  155. vmRenders.Clear();
  156. Titles.Clear();
  157. gridRender.Children.Clear();
  158. gridRender.RowDefinitions.Clear();
  159. gridRender.ColumnDefinitions.Clear();
  160. // 2) 判空
  161. if (obj == null || obj.Count == 0) return;
  162. // 3) 限制最大 16(防止越界)
  163. int count = Math.Min(obj.Count, 16);
  164. // 4) 计算行列(最大 4*4)
  165. GetGridSize(count, out int rows, out int cols);
  166. // 5) 创建主Grid的行列
  167. for (int r = 0; r < rows; r++)
  168. gridRender.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
  169. for (int c = 0; c < cols; c++)
  170. gridRender.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
  171. gridRender.ShowGridLines = true;
  172. // 6) 逐个创建子格子(每个子格子两行:标题/画面)
  173. for (int i = 0; i < count; i++)
  174. {
  175. var sr = obj[i];
  176. // (1) 创建显示控件(WindowsFormsHost + CogRecordDisplay)
  177. var disp = new CogRecordDisplay()
  178. {
  179. Tag = sr.ProceductName,
  180. };
  181. disp.HandleCreated += (s, e) =>
  182. {
  183. try
  184. {
  185. ConfigureCogDisplay(disp); // 句柄创建后再配置,最稳
  186. // 绑定 WinForms 双击事件
  187. //disp.MouseDoubleClick += (r, w) =>
  188. //{
  189. // try
  190. // {
  191. // OnDisplayDoubleClick(disp);
  192. // }
  193. // catch (Exception ex)
  194. // {
  195. // LogHelper.WriteLogError("双击预览弹窗出错", ex);
  196. // }
  197. //};
  198. }
  199. catch (Exception ex)
  200. {
  201. LogHelper.WriteLogError("ConfigureCogDisplay 失败", ex);
  202. }
  203. };
  204. var host = new WindowsFormsHost()
  205. {
  206. Tag = sr.ProceductName,
  207. Child = disp
  208. };
  209. vmRenders.Add(sr.Id, host);
  210. // (2) 创建标题
  211. var title = new TextBlock()
  212. {
  213. Text = sr.ProceductName,
  214. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  215. FontWeight = FontWeights.Bold,
  216. FontFamily = font,
  217. FontSize = 12,
  218. Foreground = System.Windows.Media.Brushes.Black
  219. };
  220. Titles.Add(sr.Id, title);
  221. // (3) 子Grid(标题 + 显示)
  222. var cell = new Grid();
  223. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) }); // 标题
  224. cell.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); // 图像
  225. cell.Children.Add(title);
  226. cell.Children.Add(host);
  227. Grid.SetRow(title, 0);
  228. Grid.SetColumn(title, 0);
  229. Grid.SetRow(host, 1);
  230. Grid.SetColumn(host, 0);
  231. // (4) 放到主 gridRender 中
  232. int row = i / cols;
  233. int col = i % cols;
  234. gridRender.Children.Add(cell);
  235. Grid.SetRow(cell, row);
  236. Grid.SetColumn(cell, col);
  237. }
  238. }
  239. /// <summary>
  240. /// 根据数量返回最合适的 rows/cols(最大 4*4)
  241. /// </summary>
  242. private void GetGridSize(int count, out int rows, out int cols)
  243. {
  244. rows = 1;
  245. cols = 1;
  246. if (count <= 1) { rows = 1; cols = 1; return; }
  247. if (count <= 2) { rows = 1; cols = 2; return; }
  248. if (count <= 4) { rows = 2; cols = 2; return; }
  249. if (count <= 6) { rows = 2; cols = 3; return; }
  250. if (count <= 9) { rows = 3; cols = 3; return; }
  251. if (count <= 12) { rows = 3; cols = 4; return; }
  252. rows = 4;
  253. cols = 4;
  254. }
  255. /// <summary>
  256. /// 统一配置 VisionPro 显示属性
  257. /// </summary>
  258. private void ConfigureCogDisplay(CogRecordDisplay disp)
  259. {
  260. disp.HorizontalScrollBar = false;
  261. disp.VerticalScrollBar = false;
  262. disp.AutoFit = true;
  263. disp.AutoFitWithGraphics = true;
  264. disp.BackColor = System.Drawing.SystemColors.ActiveCaption;
  265. }
  266. // ======================= 【新增】安全保存入口:解决闪退 =======================
  267. private void RequestSaveImage(ShowRender render, CogRecordDisplay disp)
  268. {
  269. if (render == null) return;
  270. if (disp == null) return;
  271. if (!render.IsSaveImage) return;
  272. // Original 模式不需要 CreateContentBitmap(你的 SaveImage 里 Original 只写 ICogImage)
  273. bool needRecordedBitmap =
  274. render.SaveImageModel == ProcedureSaveImageModel.Recorded ||
  275. render.SaveImageModel == ProcedureSaveImageModel.OriginalAndRecorded;
  276. _saveImageCts = new CancellationTokenSource();
  277. var token = _saveImageCts.Token;
  278. // 必须在控件的 UI 线程上执行 CreateContentBitmap
  279. disp.BeginInvoke(new Action(() =>
  280. {
  281. Bitmap clonedBitmap = null;
  282. try
  283. {
  284. token.ThrowIfCancellationRequested();
  285. if (needRecordedBitmap)
  286. {
  287. // UI线程创建
  288. Bitmap uiBitmap = (Bitmap)disp.CreateContentBitmap(
  289. Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
  290. // 立刻 Clone,后台线程只用 Clone(防止控件刷新/释放导致崩溃)
  291. clonedBitmap = (Bitmap)uiBitmap.Clone();
  292. // UI线程立刻释放
  293. uiBitmap.Dispose();
  294. }
  295. // 后台保存(限并发,防止GDI/内存瞬时飙升)
  296. Task.Run(async () =>
  297. {
  298. await _saveSemaphore.WaitAsync(token);
  299. try
  300. {
  301. token.ThrowIfCancellationRequested();
  302. SaveImage(
  303. render.SaveImageModel,
  304. render.SaveImagePathModel,
  305. render.SavePath,
  306. render.Image,
  307. clonedBitmap,
  308. render.Result,
  309. render.IsCompress
  310. );
  311. }
  312. catch (OperationCanceledException)
  313. {
  314. // 取消属于正常情况,不记录
  315. }
  316. catch (Exception ex)
  317. {
  318. LogHelper.WriteLogError("后台保存图像任务出错!", ex);
  319. }
  320. finally
  321. {
  322. // 确保释放 Clone 的 Bitmap,避免 GDI 泄漏导致闪退
  323. try { clonedBitmap?.Dispose(); } catch { }
  324. _saveSemaphore.Release();
  325. }
  326. }, token);
  327. }
  328. catch (OperationCanceledException)
  329. {
  330. try { clonedBitmap?.Dispose(); } catch { }
  331. }
  332. catch (Exception ex)
  333. {
  334. try { clonedBitmap?.Dispose(); } catch { }
  335. LogHelper.WriteLogError("RequestSaveImage(UI截图阶段) 出错!", ex);
  336. }
  337. }));
  338. }
  339. /// <summary>
  340. /// 保存图像(保持你原有逻辑不变,补充 Dispose 兜底,防止压缩分支不释放导致闪退)
  341. /// </summary>
  342. /// <param name="saveImageModel">要保存图像的模式</param>
  343. /// <param name="saveImagePathModel">图像保存路径类型</param>
  344. /// <param name="path">保存图像的文件夹路径</param>
  345. /// <param name="image">原图像</param>
  346. /// <param name="reimage">渲染图像</param>
  347. /// <param name="result">拍照结果</param>
  348. /// <param name="isCompress">是否压缩</param>
  349. private void SaveImage(ProcedureSaveImageModel saveImageModel, ProcedureSaveImagePathModel saveImagePathModel, string path, ICogImage image, Bitmap reimage, bool result, bool isCompress, ImageParameters imgPara)
  350. {
  351. if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path))
  352. {
  353. _eventAggregator.GetEvent<TaskMessageNotification>()
  354. .Publish(new Models.MessageStruct() { Message = "保存图像路径为无效的路径!", level = MessageLevel.Alarm });
  355. return;
  356. }
  357. Task.Run(() =>
  358. {
  359. try
  360. {
  361. DateTime now = DateTime.Now;
  362. if (saveImageModel == ProcedureSaveImageModel.Original)
  363. {
  364. string Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  365. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  366. {
  367. Originalpath = result
  368. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
  369. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  370. }
  371. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  372. {
  373. if (result)
  374. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  375. else
  376. return;
  377. }
  378. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  379. {
  380. if (!result)
  381. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  382. else
  383. return;
  384. }
  385. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  386. {
  387. // 当前产品配方名(过滤非法字符)
  388. string formulaName = _productService.GetCurrentProduct().Name;
  389. foreach (char c in Path.GetInvalidFileNameChars())
  390. formulaName = formulaName.Replace(c, '_');
  391. // 产品SN(过滤非法字符)
  392. string productSN = _productService.CurrentProductCode;
  393. foreach (char c in Path.GetInvalidFileNameChars())
  394. productSN = productSN.Replace(c, '_');
  395. string resultStr = result ? "OK" : "NG";
  396. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  397. }
  398. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  399. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  400. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  401. {
  402. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  403. _cogImageFileTool.Append(image);
  404. _cogImageFileTool.Close();
  405. }
  406. }
  407. else if (saveImageModel == ProcedureSaveImageModel.Recorded)
  408. {
  409. string Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  410. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  411. {
  412. Recordedpath = result
  413. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp"
  414. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  415. }
  416. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  417. {
  418. if (result)
  419. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  420. else
  421. return;
  422. }
  423. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  424. {
  425. if (!result)
  426. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  427. else
  428. return;
  429. }
  430. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  431. {
  432. string formulaName = _productService.GetCurrentProduct().Name;
  433. foreach (char c in Path.GetInvalidFileNameChars())
  434. formulaName = formulaName.Replace(c, '_');
  435. string productSN = _productService.CurrentProductCode;
  436. foreach (char c in Path.GetInvalidFileNameChars())
  437. productSN = productSN.Replace(c, '_');
  438. string resultStr = result ? "OK" : "NG";
  439. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  440. }
  441. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  442. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  443. if (isCompress)
  444. {
  445. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  446. }
  447. else
  448. {
  449. reimage.Save(Recordedpath);
  450. }
  451. }
  452. else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
  453. {
  454. string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  455. string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  456. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  457. {
  458. if (result)
  459. {
  460. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  461. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  462. }
  463. else
  464. {
  465. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  466. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  467. }
  468. }
  469. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  470. {
  471. if (result)
  472. {
  473. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  474. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  475. }
  476. else
  477. {
  478. return;
  479. }
  480. }
  481. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  482. {
  483. if (!result)
  484. {
  485. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  486. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{now:yyyy-MM-dd HH_mm_ss}.bmp";
  487. }
  488. else
  489. {
  490. return;
  491. }
  492. }
  493. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  494. {
  495. string formulaName = _productService.GetCurrentProduct().Name;
  496. foreach (char c in Path.GetInvalidFileNameChars())
  497. formulaName = formulaName.Replace(c, '_');
  498. string productSN = _productService.CurrentProductCode;
  499. foreach (char c in Path.GetInvalidFileNameChars())
  500. productSN = productSN.Replace(c, '_');
  501. string resultStr = result ? "OK" : "NG";
  502. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  503. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{productSN}-{now:yyyy-MM-dd HH_mm_ss}-{resultStr}.bmp";
  504. }
  505. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  506. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  507. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  508. {
  509. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  510. _cogImageFileTool.Append(image);
  511. _cogImageFileTool.Close();
  512. }
  513. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  514. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  515. if (isCompress)
  516. {
  517. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  518. }
  519. else
  520. {
  521. reimage.Save(Recordedpath);
  522. }
  523. }
  524. }
  525. catch (Exception ex)
  526. {
  527. LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
  528. }
  529. finally
  530. {
  531. // ======================= 【关键修复】无论是否压缩都释放Bitmap =======================
  532. try { reimage?.Dispose(); } catch { }
  533. }
  534. });
  535. }
  536. /// <summary>
  537. /// 切换产品时清空主页显示(保持你原有逻辑)
  538. /// </summary>
  539. private void ProductChanged(ProductModel product)
  540. {
  541. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  542. {
  543. foreach (var item in vmRenders)
  544. {
  545. try
  546. {
  547. if (item.Value?.Child is CogRecordDisplay disp)
  548. {
  549. if (disp.Tag != null)
  550. {
  551. disp.Image = null;
  552. disp.StaticGraphics.Clear();
  553. // 你原来 break 只清一次;这里保留你的行为
  554. break;
  555. }
  556. }
  557. }
  558. catch (Exception ex)
  559. {
  560. LogHelper.WriteLogError(Lang.切换产品清除主页图像时出错, ex);
  561. }
  562. }
  563. }));
  564. }
  565. private void OnDisplayDoubleClick(CogRecordDisplay disp)
  566. {
  567. if (disp == null) return;
  568. // 必须在 WinForms/ActiveX 线程截图
  569. disp.BeginInvoke(new Action(() =>
  570. {
  571. Bitmap bmp = null;
  572. try
  573. {
  574. if (disp.IsDisposed || !disp.IsHandleCreated)
  575. return;
  576. // 优先使用显示内容截图(带图形/record叠加)
  577. try
  578. {
  579. var uiBmp = (Bitmap)disp.CreateContentBitmap(
  580. Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
  581. bmp = (Bitmap)uiBmp.Clone();
  582. uiBmp.Dispose();
  583. }
  584. catch
  585. {
  586. // 如果 ActiveX 状态不允许截图,退化:尝试从 Image 转 Bitmap
  587. bmp = TryConvertCogImageToBitmap(disp.Image);
  588. }
  589. if (bmp == null) return;
  590. // 回到 WPF UI 线程弹窗
  591. this.Dispatcher.BeginInvoke(new Action(() =>
  592. {
  593. //var win = new ImagePreviewWindow(bmp, $"预览:{disp.Tag ?? "Display"}");
  594. //win.Owner = Window.GetWindow(this); // 让弹窗归属当前窗口
  595. //win.Show();
  596. }));
  597. }
  598. catch (Exception ex)
  599. {
  600. LogHelper.WriteLogError("OnDisplayDoubleClick 截图/弹窗出错", ex);
  601. }
  602. finally
  603. {
  604. // 这里 bmp 不要 Dispose,因为传给窗口了
  605. // 窗口关闭时会释放
  606. }
  607. }));
  608. }
  609. /// <summary>
  610. /// 将 VisionPro 的 ICogImage 尝试转换成 Bitmap(作为 CreateContentBitmap 失败时的兜底)
  611. /// </summary>
  612. private Bitmap TryConvertCogImageToBitmap(ICogImage cogImage)
  613. {
  614. try
  615. {
  616. if (cogImage == null) return null;
  617. // VisionPro 常用转换:CogImage8Grey / CogImage24PlanarColor / CogImage24PackedColor 等
  618. // 这里给通用兜底:用 CogImageFileBMP 落地到内存流,再读回 Bitmap
  619. using (var ms = new MemoryStream())
  620. {
  621. // 需要引用 Cognex.VisionPro.ImageFile
  622. using (var bmpFile = new CogImageFileBMP())
  623. {
  624. // CogImageFileBMP 只能写文件路径,不直接写流
  625. // 所以用临时文件方式最稳(如你不想落盘,可以另写转换器)
  626. var tmp = Path.Combine(Path.GetTempPath(), $"vp_preview_{Guid.NewGuid():N}.bmp");
  627. try
  628. {
  629. bmpFile.Open(tmp, CogImageFileModeConstants.Write);
  630. bmpFile.Append(cogImage);
  631. bmpFile.Close();
  632. var bitmap = (Bitmap)Bitmap.FromFile(tmp);
  633. return (Bitmap)bitmap.Clone();
  634. }
  635. finally
  636. {
  637. try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
  638. }
  639. }
  640. }
  641. }
  642. catch
  643. {
  644. return null;
  645. }
  646. }
  647. }
  648. }