使用C# 监控工业相机在文件夹新增的照片,并存储到数据库

最近接到某电子厂一个需求:检测工件。通过工业相机每次对工件拍3张照片,并通过扫码枪的扫码信号将照片和二维码信息一起存储到数据库。

工业应用大多依赖于Windows平台,Windows上天然集成了.net运行时,封装简化了win32API,使用C# +Sqlsugar+serialPort 就能轻松实现以上需求。

在C# 中,提供了

        public MyPageOne(ServiceProvider sp)
        {
            InitializeComponent();
            this.sp = sp;
            this.helper = sp.GetService<SqlSugarHelper>();
            // 创建 FileSystemWatcher 实例
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = folderPath;
            watcher.Created += Watcher_Created;
            watcher.EnableRaisingEvents = true;
        }

这样的事件监控文件新增,同理还有文件改动,删减等。

事件中写入:

        private void Watcher_Created(object sender, FileSystemEventArgs e)
        {
            // 提取新增文件的文件名
            //string fileName = Path.GetFileName(e.FullPath);
            //Console.WriteLine($"新增文件:{fileName}");
            if (IsImageFile(e.FullPath) && newFiles.Count < 3)
            {
                newFiles.Add(e.FullPath);
                //newFiles.Add(fileName);
            }

            //以下放入扫码枪事件,写入就删除
            if (newFiles.Count == 3)
            {
                //Console.WriteLine("当前新增文件:");
                foreach (string file in newFiles)
                {
                    byte[] newImageBytes = File.ReadAllBytes(file);
                    PicByte picByte = new PicByte();
                    picByte.InsertTime = DateTime.Now;

                    picByte.MyValue = newImageBytes;
                    helper.Db.Insertable<PicByte>(picByte).ExecuteCommand();
                }
                newFiles = null;
                newFiles = new List<string>();
            }
            //以上放入扫码枪事件,写入就删除
        }

查询和工具函数:

        private void BtnQueryById_Click(object sender, EventArgs e)
        {
            string id = textBox1.Text.Trim();
            byte[] imagebytes = null;
            SqlSugarHelper helper = sp.GetService<SqlSugarHelper>();

            if (id != null)
            {
                imagebytes = helper.Db.Queryable<PicByte>().Where(x => x.Id == long.Parse(id)).Select(x => x.MyValue).First();

                //MemoryStream ms = new MemoryStream(imagebytes);
                //Bitmap bmpt = new Bitmap(ms);
                //this.PicBox.Image = bmpt;

                PicBox.Image = ConvertToImage(imagebytes);
            }

        }


        private bool IsImageFile(string filePath)
        {
            string extension = Path.GetExtension(filePath).ToLower();
            return extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp";
        }

        private Image ConvertToImage(byte[] imageData)
        {
            using (MemoryStream memoryStream = new MemoryStream(imageData))
            {
                return Image.FromStream(memoryStream);
            }
        }
namespace 楷新.SqlSugar
{
    public interface ISqlSugarService
    {
        string ConnectionStr { get; set; }
    }
}

namespace 楷新.SqlSugar.Impl
{
    public class SqlSugarService : ISqlSugarService
    {
        //private string connectionStr = "Data Source=MyDb.db";
        private string connectionStr = "database='" + "mmallss" + "';Data Source = '" + "127.0.0.1" + "'; User Id = '" + "root" + "'; pwd='" + "123456" + "';charset='utf8mb4';pooling=true";


        public string ConnectionStr
        {
            get { return connectionStr; }
            set { connectionStr = value; }
        }
    }
}
using SqlSugar;

namespace 楷新.SqlSugar
{
    public interface ISqlSugarHelper
    {
        SqlSugarClient Db { get; }
    }
}

using SqlSugar;

namespace 楷新.SqlSugar.Impl
{
    public class SqlSugarHelper : ISqlSugarHelper
    {
        public SqlSugarHelper()
        {

        }
        public SqlSugarHelper(SqlSugarService sqlSugarService)
        {
            this.sqlSugarService = sqlSugarService;
        }

        private SqlSugarService sqlSugarService;
        public SqlSugarClient Db
        {
            get => new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = this.sqlSugarService.ConnectionStr,
                //DbType = DbType.Sqlite,         //必填, 数据库类型
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,       //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                InitKeyType = InitKeyType.Attribute    //默认SystemTable, codefist需要使用Attribute
            });
        }
    }
}

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Windows.Forms;
using 楷新.PLC.Modbus;
using 楷新.PLC.Modbus.Impl;
using 楷新.Robot.Fanuc;
using 楷新.Robot.Fanuc.Utils;
using 楷新.Service;
using 楷新.Service.Impl;
using 楷新.Splash;
using 楷新.SqlSugar.Impl;

namespace 楷新
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            ServiceCollection services = new ServiceCollection();
            services.AddScoped<IOnlyRun, OnlyRun>();
            services.AddScoped<SqlSugarService>();
            services.AddScoped<SqlSugarHelper>();
            services.AddScoped<CoreData>();
            services.AddScoped<MyXyzPwrArr>();
            services.AddScoped<MyAlarmArr>();
            services.AddScoped<MyDIArr>();
            services.AddScoped<MyDOArr>();
            services.AddScoped<MyRArr>();
            services.AddScoped<MyFanucAxisData>();
            services.AddScoped<IModbusHelper, ModbusHelper>();
            
            services.AddScoped<IScannerService, ScannerServiceImpl>();
            ServiceProvider sp = services.BuildServiceProvider();

            IOnlyRun onlyRun = sp.GetService<IOnlyRun>();

            if (!onlyRun.Mutex.WaitOne(0, false))
            {
                MessageBox.Show("控制系统已经运行!", "系统运行", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Application.Exit();
                return;
            }
            else
            {
                Splasher.Show(typeof(FrmSplash));
                Application.Run(new FrmMain(sp));
                //FrmLogin objFrm = new FrmLogin(sqlSugarHelper);
                //objFrm.TopMost = true;
                //if (objFrm.ShowDialog() == DialogResult.OK)
                //{
                //    Application.Run(frmMain);
                //}
                //else
                //{
                //    Application.Exit();
                //}
            }

        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值