ShowVisionRender.xaml.cs 33 KB

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