ShowVisionRender.xaml.cs 32 KB

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