ShowVisionRender.xaml.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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.DoubleClick += (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. foreach (char c in Path.GetInvalidFileNameChars())
  423. productSN = productSN.Replace(c, '_');
  424. string resultStr = result ? "OK" : "NG";
  425. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  426. }
  427. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  428. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  429. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  430. {
  431. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  432. _cogImageFileTool.Append(image);
  433. _cogImageFileTool.Close();
  434. }
  435. }
  436. else if (saveImageModel == ProcedureSaveImageModel.Recorded)
  437. {
  438. string Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  439. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  440. {
  441. Recordedpath = result
  442. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp"
  443. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  444. }
  445. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  446. {
  447. if (result)
  448. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  449. else
  450. return;
  451. }
  452. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  453. {
  454. if (!result)
  455. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  456. else
  457. return;
  458. }
  459. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  460. {
  461. string formulaName = _productService.GetCurrentProduct().Name;
  462. foreach (char c in Path.GetInvalidFileNameChars())
  463. formulaName = formulaName.Replace(c, '_');
  464. string productSN = _productService.CurrentProductCode;
  465. foreach (char c in Path.GetInvalidFileNameChars())
  466. productSN = productSN.Replace(c, '_');
  467. string resultStr = result ? "OK" : "NG";
  468. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  469. }
  470. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  471. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  472. if (isCompress)
  473. {
  474. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  475. }
  476. else
  477. {
  478. reimage.Save(Recordedpath);
  479. }
  480. }
  481. else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
  482. {
  483. string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  484. string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  485. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  486. {
  487. if (result)
  488. {
  489. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  490. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  491. }
  492. else
  493. {
  494. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  495. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  496. }
  497. }
  498. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  499. {
  500. if (result)
  501. {
  502. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  503. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  504. }
  505. else
  506. {
  507. return;
  508. }
  509. }
  510. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  511. {
  512. if (!result)
  513. {
  514. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  515. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  516. }
  517. else
  518. {
  519. return;
  520. }
  521. }
  522. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  523. {
  524. string formulaName = _productService.GetCurrentProduct().Name;
  525. foreach (char c in Path.GetInvalidFileNameChars())
  526. formulaName = formulaName.Replace(c, '_');
  527. string productSN = _productService.CurrentProductCode;
  528. if (!string.IsNullOrEmpty(productSN))
  529. {
  530. foreach (char c in Path.GetInvalidFileNameChars())
  531. productSN = productSN.Replace(c, '_');
  532. }
  533. string resultStr = result ? "OK" : "NG";
  534. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  535. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  536. }
  537. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  538. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  539. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  540. {
  541. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  542. _cogImageFileTool.Append(image);
  543. _cogImageFileTool.Close();
  544. }
  545. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  546. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  547. if (isCompress)
  548. {
  549. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  550. }
  551. else
  552. {
  553. reimage.Save(Recordedpath);
  554. }
  555. }
  556. }
  557. catch (Exception ex)
  558. {
  559. LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
  560. }
  561. finally
  562. {
  563. // ======================= 【关键修复】无论是否压缩都释放Bitmap =======================
  564. try { reimage?.Dispose(); } catch { }
  565. }
  566. });
  567. }
  568. /// <summary>
  569. /// 切换产品时清空主页显示(保持你原有逻辑)
  570. /// </summary>
  571. private void ProductChanged(ProductModel product)
  572. {
  573. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  574. {
  575. foreach (var item in vmRenders)
  576. {
  577. try
  578. {
  579. if (item.Value?.Child is CogRecordDisplay disp)
  580. {
  581. if (disp.Tag != null)
  582. {
  583. disp.Image = null;
  584. disp.StaticGraphics.Clear();
  585. // 你原来 break 只清一次;这里保留你的行为
  586. break;
  587. }
  588. }
  589. }
  590. catch (Exception ex)
  591. {
  592. LogHelper.WriteLogError(Lang.切换产品清除主页图像时出错, ex);
  593. }
  594. }
  595. }));
  596. }
  597. private void OnDisplayDoubleClick(CogRecordDisplay disp)
  598. {
  599. if (disp == null) return;
  600. // 必须在 WinForms/ActiveX 线程截图
  601. disp.BeginInvoke(new Action(() =>
  602. {
  603. Bitmap bmp = null;
  604. try
  605. {
  606. if (disp.IsDisposed || !disp.IsHandleCreated)
  607. return;
  608. // 优先使用显示内容截图(带图形/record叠加)
  609. try
  610. {
  611. var uiBmp = (Bitmap)disp.CreateContentBitmap(
  612. Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
  613. bmp = (Bitmap)uiBmp.Clone();
  614. uiBmp.Dispose();
  615. }
  616. catch
  617. {
  618. // 如果 ActiveX 状态不允许截图,退化:尝试从 Image 转 Bitmap
  619. bmp = TryConvertCogImageToBitmap(disp.Image);
  620. }
  621. if (bmp == null) return;
  622. // 回到 WPF UI 线程弹窗
  623. this.Dispatcher.BeginInvoke(new Action(() =>
  624. {
  625. viewModel.ShowImage(disp);
  626. }));
  627. }
  628. catch (Exception ex)
  629. {
  630. LogHelper.WriteLogError("OnDisplayDoubleClick 截图/弹窗出错", ex);
  631. }
  632. finally
  633. {
  634. // 这里 bmp 不要 Dispose,因为传给窗口了
  635. // 窗口关闭时会释放
  636. }
  637. }));
  638. }
  639. /// <summary>
  640. /// 将 VisionPro 的 ICogImage 尝试转换成 Bitmap(作为 CreateContentBitmap 失败时的兜底)
  641. /// </summary>
  642. private Bitmap TryConvertCogImageToBitmap(ICogImage cogImage)
  643. {
  644. try
  645. {
  646. if (cogImage == null) return null;
  647. // VisionPro 常用转换:CogImage8Grey / CogImage24PlanarColor / CogImage24PackedColor 等
  648. // 这里给通用兜底:用 CogImageFileBMP 落地到内存流,再读回 Bitmap
  649. using (var ms = new MemoryStream())
  650. {
  651. // 需要引用 Cognex.VisionPro.ImageFile
  652. using (var bmpFile = new CogImageFileBMP())
  653. {
  654. // CogImageFileBMP 只能写文件路径,不直接写流
  655. // 所以用临时文件方式最稳(如你不想落盘,可以另写转换器)
  656. var tmp = Path.Combine(Path.GetTempPath(), $"vp_preview_{Guid.NewGuid():N}.bmp");
  657. try
  658. {
  659. bmpFile.Open(tmp, CogImageFileModeConstants.Write);
  660. bmpFile.Append(cogImage);
  661. bmpFile.Close();
  662. var bitmap = (Bitmap)Bitmap.FromFile(tmp);
  663. return (Bitmap)bitmap.Clone();
  664. }
  665. finally
  666. {
  667. try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
  668. }
  669. }
  670. }
  671. }
  672. catch
  673. {
  674. return null;
  675. }
  676. }
  677. }
  678. }