using OpenCvSharp; using System.IO; namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Access { /// /// 保存图像To文件Handler /// public class ImageToFileHandler : IVisionFlowHandler { /// /// 类型 /// public VisionFlowType Type => VisionFlowType.存到文件; /// /// 执行 /// /// 视觉功能 /// 变量项 /// 返回布尔值 public bool Execute(VisionFunction func, VisionFlow item) { if (item.StringParams.TryGetValue("Path", out string filePath)) { try { if (item.BoolParams.TryGetValue("DateTimePath", out bool useDateTime)) { if (useDateTime) { filePath += DateTime.Now.ToString("yyyy_MM_dd"); filePath += "\\"; } } if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } var fileName = filePath + DateTime.Now.ToString("yyyy_MM_dd HH_mm_ss_ff") + ".png"; if (Cv2.ImWrite(fileName, func.Src)) { return true; } else { throw new Exception($"保存图像失败"); } } catch (Exception ex) { throw new Exception($"保存图像失败: {ex.Message}"); } } else { throw new Exception("未配置文件路径,请重新配置!"); } } } }