ShowVisionRender.xaml.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. SaveImage(
  282. render.SaveImageModel,
  283. render.SaveImagePathModel,
  284. render.SavePath,
  285. render.Image,
  286. clonedBitmap,
  287. render.Result,
  288. render.IsCompress,
  289. render.ImageFileName
  290. );
  291. }
  292. }
  293. catch (OperationCanceledException)
  294. {
  295. // 取消属于正常情况,不记录
  296. }
  297. catch (Exception ex)
  298. {
  299. LogHelper.WriteLogError("后台保存图像任务出错!", ex);
  300. }
  301. finally
  302. {
  303. // 确保释放 Clone 的 Bitmap,避免 GDI 泄漏导致闪退
  304. //try { clonedBitmap?.Dispose(); } catch { }
  305. _saveSemaphore.Release();
  306. }
  307. }, token);
  308. }
  309. catch (OperationCanceledException)
  310. {
  311. //try { clonedBitmap?.Dispose(); } catch { }
  312. }
  313. catch (Exception ex)
  314. {
  315. //try { clonedBitmap?.Dispose(); } catch { }
  316. LogHelper.WriteLogError("RequestSaveImage(UI截图阶段) 出错!", ex);
  317. }
  318. }));
  319. }
  320. private void UpdateDelaySaveImage(bool isSave)
  321. {
  322. if (!isSave)
  323. {
  324. delaySaveImages.Clear();
  325. return;
  326. }
  327. // 这里简单遍历保存,实际可以根据需要优化(如批量处理/分队列等)
  328. foreach (var item in delaySaveImages)
  329. {
  330. try
  331. {
  332. SaveImage(
  333. item.SaveImageModel,
  334. item.SaveImagePathModel,
  335. item.SavePath,
  336. item.Image,
  337. item.clonedBitmap,
  338. item.Result,
  339. item.IsCompress,
  340. item.ImageFileName
  341. );
  342. }
  343. catch (Exception ex)
  344. {
  345. LogHelper.WriteLogError("UpdateDelaySaveImage 保存图像时出错!", ex);
  346. }
  347. finally
  348. {
  349. // 保存后���放资源
  350. try { item.clonedBitmap?.Dispose(); } catch { }
  351. }
  352. }
  353. delaySaveImages.Clear();
  354. }
  355. /// <summary>
  356. /// 保存图像(保持你原有逻辑不变,补充 Dispose 兜底,防止压缩分支不释放导致闪退)
  357. /// </summary>
  358. private void SaveImage(ProcedureSaveImageModel saveImageModel, ProcedureSaveImagePathModel saveImagePathModel, string path, ICogImage image, Bitmap reimage, bool result, bool isCompress, string imageFileName)
  359. {
  360. if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path))
  361. {
  362. _eventAggregator.GetEvent<TaskMessageNotification>()
  363. .Publish(new Models.MessageStruct() { Message = "保存图像路径为无效的路径!", level = MessageLevel.Alarm });
  364. return;
  365. }
  366. Task.Run(() =>
  367. {
  368. try
  369. {
  370. DateTime now = DateTime.Now;
  371. //图片名
  372. string imgName = now.ToString("yyyy-MM-dd HH_mm_ss");
  373. if (!string.IsNullOrEmpty(imageFileName))
  374. {
  375. imgName = imageFileName;
  376. }
  377. if (saveImageModel == ProcedureSaveImageModel.Original)
  378. {
  379. string Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  380. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  381. {
  382. Originalpath = result
  383. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp"
  384. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  385. }
  386. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  387. {
  388. if (result)
  389. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  390. else
  391. return;
  392. }
  393. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  394. {
  395. if (!result)
  396. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  397. else
  398. return;
  399. }
  400. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  401. {
  402. // 当前产品配方名(过滤非法字符)
  403. string formulaName = _productService.GetCurrentProduct().Name;
  404. foreach (char c in Path.GetInvalidFileNameChars())
  405. formulaName = formulaName.Replace(c, '_');
  406. // 产品SN(过滤非法字符)
  407. string productSN = _productService.CurrentProductCode;
  408. if (!string.IsNullOrEmpty(productSN))
  409. {
  410. foreach (char c in Path.GetInvalidFileNameChars())
  411. productSN = productSN.Replace(c, '_');
  412. }
  413. string resultStr = result ? "OK" : "NG";
  414. Originalpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  415. }
  416. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  417. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  418. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  419. {
  420. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  421. _cogImageFileTool.Append(image);
  422. _cogImageFileTool.Close();
  423. }
  424. }
  425. else if (saveImageModel == ProcedureSaveImageModel.Recorded)
  426. {
  427. string Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  428. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  429. {
  430. Recordedpath = result
  431. ? $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp"
  432. : $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  433. }
  434. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  435. {
  436. if (result)
  437. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  438. else
  439. return;
  440. }
  441. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  442. {
  443. if (!result)
  444. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  445. else
  446. return;
  447. }
  448. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  449. {
  450. string formulaName = _productService.GetCurrentProduct().Name;
  451. foreach (char c in Path.GetInvalidFileNameChars())
  452. formulaName = formulaName.Replace(c, '_');
  453. string productSN = _productService.CurrentProductCode;
  454. foreach (char c in Path.GetInvalidFileNameChars())
  455. productSN = productSN.Replace(c, '_');
  456. string resultStr = result ? "OK" : "NG";
  457. Recordedpath = $"{path}\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  458. }
  459. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  460. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  461. if (isCompress)
  462. {
  463. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  464. }
  465. else
  466. {
  467. reimage.Save(Recordedpath);
  468. }
  469. }
  470. else if (saveImageModel == ProcedureSaveImageModel.OriginalAndRecorded)
  471. {
  472. string Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  473. string Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{imgName}.bmp";
  474. if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_OkNG_Time)
  475. {
  476. if (result)
  477. {
  478. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  479. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  480. }
  481. else
  482. {
  483. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  484. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  485. }
  486. }
  487. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ok_Time)
  488. {
  489. if (result)
  490. {
  491. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  492. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\OK\\{imgName}.bmp";
  493. }
  494. else
  495. {
  496. return;
  497. }
  498. }
  499. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Ng_Time)
  500. {
  501. if (!result)
  502. {
  503. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  504. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\NG\\{imgName}.bmp";
  505. }
  506. else
  507. {
  508. return;
  509. }
  510. }
  511. else if (saveImagePathModel == ProcedureSaveImagePathModel.Month_Day_Formula_ProductSN_Time)
  512. {
  513. string formulaName = _productService.GetCurrentProduct().Name;
  514. foreach (char c in Path.GetInvalidFileNameChars())
  515. formulaName = formulaName.Replace(c, '_');
  516. string productSN = _productService.CurrentProductCode;
  517. if (string.IsNullOrEmpty(productSN))
  518. {
  519. foreach (char c in Path.GetInvalidFileNameChars())
  520. productSN = productSN.Replace(c, '_');
  521. }
  522. string resultStr = result ? "OK" : "NG";
  523. Originalpath = $"{path}\\Original\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  524. Recordedpath = $"{path}\\Recored\\{now:yyyy-MM}\\{now:MM-dd}\\{formulaName}\\{productSN}\\{resultStr}\\{imgName}.bmp";
  525. }
  526. if (!Directory.Exists(Path.GetDirectoryName(Originalpath)))
  527. Directory.CreateDirectory(Path.GetDirectoryName(Originalpath));
  528. using (CogImageFileBMP _cogImageFileTool = new CogImageFileBMP())
  529. {
  530. _cogImageFileTool.Open(Originalpath, CogImageFileModeConstants.Write);
  531. _cogImageFileTool.Append(image);
  532. _cogImageFileTool.Close();
  533. }
  534. if (!Directory.Exists(Path.GetDirectoryName(Recordedpath)))
  535. Directory.CreateDirectory(Path.GetDirectoryName(Recordedpath));
  536. if (isCompress)
  537. {
  538. ImageHelper.CompressImage(reimage, Recordedpath, 100);
  539. }
  540. else
  541. {
  542. reimage.Save(Recordedpath);
  543. }
  544. }
  545. }
  546. catch (Exception ex)
  547. {
  548. LogHelper.WriteLogError("保存流程运行结果的图片时出错!", ex);
  549. }
  550. finally
  551. {
  552. // ======================= 【关键修复】无论是否压缩都释放Bitmap =======================
  553. try { reimage?.Dispose(); } catch { }
  554. }
  555. });
  556. }
  557. /// <summary>
  558. /// 切换产品时清空主页显示(保持你原有逻辑)
  559. /// </summary>
  560. private void ProductChanged(ProductModel product)
  561. {
  562. this.gridRender.Dispatcher.BeginInvoke(new Action(() =>
  563. {
  564. foreach (var item in vmRenders)
  565. {
  566. try
  567. {
  568. if (item.Value?.Child is CogRecordDisplay disp)
  569. {
  570. if (disp.Tag != null)
  571. {
  572. disp.Image = null;
  573. disp.StaticGraphics.Clear();
  574. // 你原来 break 只清一次;这里保留你的行为
  575. break;
  576. }
  577. }
  578. }
  579. catch (Exception ex)
  580. {
  581. LogHelper.WriteLogError(Lang.切换产品清除主页图像时出错, ex);
  582. }
  583. }
  584. }));
  585. }
  586. private void OnDisplayDoubleClick(CogRecordDisplay disp)
  587. {
  588. if (disp == null) return;
  589. // 必须在 WinForms/ActiveX 线程截图
  590. disp.BeginInvoke(new Action(() =>
  591. {
  592. Bitmap bmp = null;
  593. try
  594. {
  595. if (disp.IsDisposed || !disp.IsHandleCreated)
  596. return;
  597. // 优先使用显示内容截图(带图形/record叠加)
  598. try
  599. {
  600. var uiBmp = (Bitmap)disp.CreateContentBitmap(
  601. Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Custom);
  602. bmp = (Bitmap)uiBmp.Clone();
  603. uiBmp.Dispose();
  604. }
  605. catch
  606. {
  607. // 如果 ActiveX 状态不允许截图,退化:尝试从 Image 转 Bitmap
  608. bmp = TryConvertCogImageToBitmap(disp.Image);
  609. }
  610. if (bmp == null) return;
  611. // 回到 WPF UI 线程弹窗
  612. this.Dispatcher.BeginInvoke(new Action(() =>
  613. {
  614. //var win = new ImagePreviewWindow(bmp, $"预览:{disp.Tag ?? "Display"}");
  615. //win.Owner = Window.GetWindow(this); // 让弹窗归属当前窗口
  616. //win.Show();
  617. }));
  618. }
  619. catch (Exception ex)
  620. {
  621. LogHelper.WriteLogError("OnDisplayDoubleClick 截图/弹窗出错", ex);
  622. }
  623. finally
  624. {
  625. // 这里 bmp 不要 Dispose,因为传给窗口了
  626. // 窗口关闭时会释放
  627. }
  628. }));
  629. }
  630. /// <summary>
  631. /// 将 VisionPro 的 ICogImage 尝试转换成 Bitmap(作为 CreateContentBitmap 失败时的兜底)
  632. /// </summary>
  633. private Bitmap TryConvertCogImageToBitmap(ICogImage cogImage)
  634. {
  635. try
  636. {
  637. if (cogImage == null) return null;
  638. // VisionPro 常用转换:CogImage8Grey / CogImage24PlanarColor / CogImage24PackedColor 等
  639. // 这里给通用兜底:用 CogImageFileBMP 落地到内存流,再读回 Bitmap
  640. using (var ms = new MemoryStream())
  641. {
  642. // 需要引用 Cognex.VisionPro.ImageFile
  643. using (var bmpFile = new CogImageFileBMP())
  644. {
  645. // CogImageFileBMP 只能写文件路径,不直接写流
  646. // 所以用临时文件方式最稳(如你不想落盘,可以另写转换器)
  647. var tmp = Path.Combine(Path.GetTempPath(), $"vp_preview_{Guid.NewGuid():N}.bmp");
  648. try
  649. {
  650. bmpFile.Open(tmp, CogImageFileModeConstants.Write);
  651. bmpFile.Append(cogImage);
  652. bmpFile.Close();
  653. var bitmap = (Bitmap)Bitmap.FromFile(tmp);
  654. return (Bitmap)bitmap.Clone();
  655. }
  656. finally
  657. {
  658. try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
  659. }
  660. }
  661. }
  662. }
  663. catch
  664. {
  665. return null;
  666. }
  667. }
  668. }
  669. }