ShowVisionRender.xaml.cs 32 KB

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