2019-05-04 10:26:13 qq_33869371 阅读数 459
  • C#急速入门

    Unity开发,C#绝对是基础中的基础,课程针对纯小白而设计,各种语言细节在课程里均有涉猎,从原理到实战,从底层到算法,你想了解的C#,这里应有尽有,除了讲解,还有练习,你说棒不棒,哈哈,当然如果你是有其他语言基础的同学,课程依然会让你收货满满。来吧,我们进入正题。

    13672 人正在学习 去看看 张建飞

1、C# 多个ip摄像头画面预览以及截图界面

2、winform VS2013 .NET4 Client Profile

3、测试摄像头:海康威视,USB摄像头

4、需要输入IP地址,端口号,用户名和密码。预览、抓图、客户端录像基本功能,其中抓图包括BMP和JPEG抓图(包括抓图保存在缓冲区中)。

5、IP通道设置(添加、修改、删除)功能。

 以下为主窗体代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Timers;
using System.Configuration;
//using System.Date

namespace NVRCsharpDemo
{
    
    public partial class MainWindow : Form
    {
        private bool m_bInitSDK = false;
        //private bool m_bRecord = false;
        private uint iLastErr = 0;
    
        private string str1;
        private string str2;
        private Int32 i = 0;
        private Int32 m_lTree=0;
        private string str;
        private long iSelIndex = 0;
        private uint dwAChanTotalNum = 0;
        private Int32 m_tokenWrite = -1;
        public int m_lChannel = -1;
        //private Int32 m_lPort = -1;
        //private IntPtr m_ptrRealHandle;
        private int[] iIPDevID = new int[96];
        private int[] iChannelNum = new int[96];
        private string curTime;
        private int deviceNum = 0;
        private string savePath1;
        private string savePath2;
        private string savePath3;
        //private double picTime;

        private CHCNetSDK.REALDATACALLBACK RealData = null;
        public CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo;
     
        private string m_token;
        public CHCNetSDK.NET_DVR_IPPARACFG_V40 m_struIpParaCfgV40;
        public CHCNetSDK.NET_DVR_STREAM_MODE m_struStreamMode;
        public CHCNetSDK.NET_DVR_IPCHANINFO m_struChanInfo;
        public CHCNetSDK.NET_DVR_IPCHANINFO_V40 m_struChanInfoV40;
        private PlayCtrl.DECCBFUN m_fDisplayFun = null;
        public delegate void MyDebugInfo(string str);
        //public string GetTimeStamp();

        //private Int32 pic_Num = 0;
        public MyDeviceInfo DV1 = new MyDeviceInfo { IPAddress = "192.168.1.230", PortNumber= 8080,num = 1,picTime=60, m_lUserID = -1, m_lRealHandle = -1 };
        public MyDeviceInfo DV2 = new MyDeviceInfo { IPAddress = "192.168.11.252", PortNumber = 8080, num = 2, picTime = 60, m_lUserID = -1, m_lRealHandle = -1 };
        public MyDeviceInfo DV3 = new MyDeviceInfo { num = 3, picTime = 60, m_lUserID = -1, m_lRealHandle = -1 };
        private int isDevice = -1;

        public class MyDeviceInfo
        {
            public int num;
            public string token { get; set; }
            public string IPAddress { get; set; }
            public Int32 PortNumber { get; set; }
            public string DeviceID { get; set; }
            public double picTime { get; set; }

            public Int32 m_lUserID { get; set; }
            public Int32 m_lRealHandle { get; set; }
            public string DVRUserName { get; set; }
            public string DVRPassword { get; set; }
           // public int[] iChannelNum = new int[96];
            public void Init()
            {

            }

        }

        public MainWindow()
        {
            InitializeComponent();
            //btnLogin.Enabled = false;
            //textBoxIP.Enabled = false;
            //textBoxPort.Enabled = false;
            //textBoxPicTime.Enabled = false;
            //textBoxUser.Enabled = false;
            //textBoxPassword.Enabled = false;
            btnJPEG.Enabled = false;

            m_bInitSDK = CHCNetSDK.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                MessageBox.Show("NET_DVR_Init error!");
                return;
            }
            else
            {
                //保存SDK日志 To save the SDK log
                CHCNetSDK.NET_DVR_SetLogToFile(3,"C:\\SdkLog\\", true);

                //comboBoxView.SelectedIndex = 0;
                
                for (int i = 0; i < 64; i++)
                {
                    iIPDevID[i] = -1;
                    iChannelNum[i] = -1;
                }
            }
            //UpdateAppConfig("FilePath", System.Environment.CurrentDirectory);
        }

        //public void DebugInfo(string str)
        //{
        //    if (str.Length > 0)
        //    {
        //        str += "\n";
        //        TextBoxInfo.AppendText(str);
        //    }
        //}
        //private System.Windows.Forms.PictureBox WindowSelect(int i)
        //{
        //    switch (i)
        //    { 
        //        case 1:
        //        return 
            
        //    }
        //}
        private void DeviceSelect(MyDeviceInfo DV) {
            if (DV.m_lUserID < 0)
            {
                DV.IPAddress = textBoxIP.Text; //设备IP地址或者域名 Device IP
                DV.PortNumber = Int16.Parse(textBoxPort.Text);//设备服务端口号 Device Port
                DV.DVRUserName = textBoxUser.Text;//设备登录用户名 User name to login             
                DV.DVRPassword = textBoxPassword.Text;//设备登录密码 Password to login

                byte[] GetIPAddress = new byte[16];

                //登录设备 Login the device
                DV.m_lUserID = CHCNetSDK.NET_DVR_Login_V30(DV.IPAddress, DV.PortNumber, DV.DVRUserName, DV.DVRPassword, ref DeviceInfo);
                if (DV.m_lUserID < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败,输出错误号 Failed to login and output the error code
                    MessageBox.Show("登陆失败!");
                    return;
                }
                else
                {
                    textBoxPicTime.Enabled = true;
                    btnJPEG.Enabled = true;
                    //登录成功
                    btnLogin.Text = "退出";
                
                    textBoxIP.Enabled = false;
                    textBoxPort.Enabled = false;                 
                    textBoxUser.Enabled = false;
                    textBoxPassword.Enabled = false;

                    dwAChanTotalNum = (uint)DeviceInfo.byChanNum;

                    string s = System.Text.Encoding.Default.GetString(DeviceInfo.sSerialNumber);
                    s = s.Replace("\0", "");
                    DV.DeviceID = s.Substring(s.Length - 9);
                    labelDeviceID.Text = DV.DeviceID;

                    if (DeviceInfo.byIPChanNum > 0)
                    {
                        InfoIPChannel(DV);
                    }
                    else
                    {
                        for (i = 0; i < dwAChanTotalNum; i++)
                        {
                            ListAnalogChannel(i + 1, 1);
                            iChannelNum[i] = i + (int)DeviceInfo.byStartChan;
                        }
                    }
                }
                //开始预览
                if (DV.m_lRealHandle < 0)
                {
                    CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                    if (DV.num == 1)
                    {
                        lpPreviewInfo.hPlayWnd = RealPlayWnd1.Handle;//预览窗口-1 live view window
                    }
                    else if (DV.num == 2) {
                        lpPreviewInfo.hPlayWnd = RealPlayWnd2.Handle;//预览窗口 live view window
                    }
                    else if (DV.num == 3)
                    {
                        lpPreviewInfo.hPlayWnd = RealPlayWnd3.Handle;//预览窗口 live view window
                    }
                  
                    lpPreviewInfo.lChannel = iChannelNum[(int)iSelIndex];//预览的设备通道 the device channel number
                    lpPreviewInfo.dwStreamType = 0;//码流类型:0-主码流,1-子码流,2-码流3,3-码流4,以此类推
                    lpPreviewInfo.dwLinkMode = 0;//连接方式:0- TCP方式,1- UDP方式,2- 多播方式,3- RTP方式,4-RTP/RTSP,5-RSTP/HTTP 
                    lpPreviewInfo.bBlocked = true; //0- 非阻塞取流,1- 阻塞取流

                    IntPtr pUser = IntPtr.Zero;//用户数据 user data 

                    //打开预览 Start live view 
                    DV.m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(DV.m_lUserID, ref lpPreviewInfo, null/*RealData*/, pUser);

                    if (DV.m_lRealHandle < 0)
                    {
                        iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                        str = "NET_DVR_RealPlay_V40 failed, error code= " + iLastErr; //预览失败,输出错误号 failed to start live view, and output the error code.
                        //DebugInfo(str);
                        Console.Write(str);
                        return;
                    }                    
                }
                if (DV.num == 1)
                {
                    UpdateAppConfig("DV1_IPAddress", DV1.IPAddress);
                    UpdateAppConfig("DV1_PortNum", DV1.PortNumber.ToString());
                    UpdateAppConfig("DV1_UserName", DV1.DVRUserName);
                    UpdateAppConfig("DV1_Password", DV1.DVRPassword);
                }
                else if (DV.num == 2)
                {
                    UpdateAppConfig("DV2_IPAddress", DV2.IPAddress);
                    UpdateAppConfig("DV2_PortNum", DV2.PortNumber.ToString());
                    UpdateAppConfig("DV2_UserName", DV2.DVRUserName);
                    UpdateAppConfig("DV2_Password", DV2.DVRPassword);
                }
                else if (DV.num == 3)
                {
                    UpdateAppConfig("DV3_IPAddress", DV3.IPAddress);
                    UpdateAppConfig("DV3_PortNum", DV3.PortNumber.ToString());
                    UpdateAppConfig("DV3_UserName", DV3.DVRUserName);
                    UpdateAppConfig("DV3_Password", DV3.DVRPassword);
                }
            }
            else if (DV.m_lUserID >= 0)
            {
                //注销登录 Logout the device
                //m_lRealHandle判断是否是在预览视频中
                //停止预览 Stop live view 
                if (DV.num == 1)
                {
                    CHCNetSDK.NET_DVR_StopRealPlay(DV1.m_lRealHandle);
                    DV1.m_lRealHandle = -1;
                    RealPlayWnd1.Invalidate();//刷新窗口-1 refresh the window     
                }
                else if (DV.num == 2)
                {
                    CHCNetSDK.NET_DVR_StopRealPlay(DV2.m_lRealHandle);
                    DV2.m_lRealHandle = -1;
                    RealPlayWnd2.Invalidate();//刷新窗口 refresh the window     
                }
                else if (DV.num == 3)
                {
                    CHCNetSDK.NET_DVR_StopRealPlay(DV3.m_lRealHandle);
                    DV3.m_lRealHandle = -1;
                    RealPlayWnd3.Invalidate();//刷新窗口 refresh the window     
                }

                //退出
                if (!CHCNetSDK.NET_DVR_Logout(DV.m_lUserID))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    str = "NET_DVR_Logout failed, error code= " + iLastErr;
                    MessageBox.Show(str);
                    //DebugInfo(str);
                    return;
                }

                Console.Write("NET_DVR_StopRealPlay succ!");
               // DV.m_lRealHandle = -1;
                    
                DV.m_lUserID = -1;
                btnLogin.Text = "登陆并预览";

                textBoxIP.Enabled = true;
                textBoxPort.Enabled = true;
                textBoxUser.Enabled = true;
                textBoxPassword.Enabled = true;
               
                //m_tokenWrite = -1;

                deviceNum -= 1;
                UpdateAppConfig("DeviceNum", deviceNum.ToString());
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            //m_lUserID用来表示是否在登陆中,大于等于0表示已经登陆   
                switch (comboBoxDevice.SelectedIndex)
                {
                    case 0:
                        DeviceSelect(DV1);
                        break;
                    case 1:
                        DeviceSelect(DV2);
                        break;
                    case 2:
                        DeviceSelect(DV3);
                        break;
                }

           return;
        }

        public void InfoIPChannel(MyDeviceInfo DV)
        {
            uint dwSize = (uint)Marshal.SizeOf(m_struIpParaCfgV40);

            IntPtr ptrIpParaCfgV40 = Marshal.AllocHGlobal((Int32)dwSize);
            Marshal.StructureToPtr(m_struIpParaCfgV40, ptrIpParaCfgV40, false);

            uint dwReturn = 0;
            int iGroupNo = 0;
            if (!CHCNetSDK.NET_DVR_GetDVRConfig(DV.m_lUserID, CHCNetSDK.NET_DVR_GET_IPPARACFG_V40, iGroupNo, ptrIpParaCfgV40, dwSize, ref dwReturn))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_GET_IPPARACFG_V40 failed, error code= " + iLastErr; 
                //获取IP资源配置信息失败,输出错误号 Failed to get configuration of IP channels and output the error code
                //DebugInfo(str);
            }
            else
            {
                m_struIpParaCfgV40 = (CHCNetSDK.NET_DVR_IPPARACFG_V40)Marshal.PtrToStructure(ptrIpParaCfgV40, typeof(CHCNetSDK.NET_DVR_IPPARACFG_V40));
               
                for (i = 0; i < dwAChanTotalNum; i++)
                {
                    ListAnalogChannel(i+1, m_struIpParaCfgV40.byAnalogChanEnable[i]);
                    iChannelNum[i] = i + (int)DeviceInfo.byStartChan;                     
                }
                
                byte byStreamType;
                for (i = 0; i < m_struIpParaCfgV40.dwDChanNum; i++)
                {
                    iChannelNum[i + dwAChanTotalNum] = i + (int)m_struIpParaCfgV40.dwStartDChan;
                    byStreamType = m_struIpParaCfgV40.struStreamMode[i].byGetStreamType;

                    dwSize = (uint)Marshal.SizeOf(m_struIpParaCfgV40.struStreamMode[i].uGetStream);
                    switch (byStreamType)
                    {
                        //目前NVR仅支持直接从设备取流 NVR supports only the mode: get stream from device directly
                        case 0:
                            IntPtr ptrChanInfo = Marshal.AllocHGlobal((Int32)dwSize);
                            Marshal.StructureToPtr(m_struIpParaCfgV40.struStreamMode[i].uGetStream, ptrChanInfo, false);
                            m_struChanInfo = (CHCNetSDK.NET_DVR_IPCHANINFO)Marshal.PtrToStructure(ptrChanInfo, typeof(CHCNetSDK.NET_DVR_IPCHANINFO));

                            //列出IP通道 List the IP channel
                            ListIPChannel(i + 1, m_struChanInfo.byEnable, m_struChanInfo.byIPID);
                            iIPDevID[i] = m_struChanInfo.byIPID + m_struChanInfo.byIPIDHigh * 256 - iGroupNo * 64 - 1;

                            Marshal.FreeHGlobal(ptrChanInfo);
                            break;
                        case 6:                            
                            IntPtr ptrChanInfoV40 = Marshal.AllocHGlobal((Int32)dwSize);
                            Marshal.StructureToPtr(m_struIpParaCfgV40.struStreamMode[i].uGetStream, ptrChanInfoV40, false);
                            m_struChanInfoV40 = (CHCNetSDK.NET_DVR_IPCHANINFO_V40)Marshal.PtrToStructure(ptrChanInfoV40, typeof(CHCNetSDK.NET_DVR_IPCHANINFO_V40));
                            
                            //列出IP通道 List the IP channel
                            ListIPChannel(i + 1, m_struChanInfoV40.byEnable, m_struChanInfoV40.wIPID);
                            iIPDevID[i] = m_struChanInfoV40.wIPID - iGroupNo * 64 - 1;

                            Marshal.FreeHGlobal(ptrChanInfoV40);
                            break;
                        default:
                            break;
                    }
                }
            }
            Marshal.FreeHGlobal(ptrIpParaCfgV40);
        
        }
        public void ListIPChannel(Int32 iChanNo, byte byOnline, int byIPID)
        {
            str1 = String.Format("IPCamera {0}", iChanNo);
            m_lTree++;

            if (byIPID == 0)
            {
                str2 = "X"; //通道空闲,没有添加前端设备 the channel is idle                  
            }
            else
            {
                if (byOnline == 0)
                {
                    str2 = "offline"; //通道不在线 the channel is off-line
                }
                else
                    str2 = "online"; //通道在线 The channel is on-line
            }

            //listViewIPChannel.Items.Add(new ListViewItem(new string[] { str1, str2 }));//将通道添加到列表中 add the channel to the list
        }
        public void ListAnalogChannel(Int32 iChanNo, byte byEnable)
        {
            str1 = String.Format("Camera {0}", iChanNo);
            m_lTree++;

            if (byEnable == 0)
            {
                str2 = "Disabled"; //通道已被禁用 This channel has been disabled               
            }
            else
            {
                str2 = "Enabled"; //通道处于启用状态 This channel has been enabled
            }

            //listViewIPChannel.Items.Add(new ListViewItem(new string[] { str1, str2 }));//将通道添加到列表中 add the channel to the list
        }

        System.Timers.Timer myTimer;
       
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string Time = Convert.ToInt64(ts.TotalSeconds).ToString();
            //DateTime DT = System.DateTime.Now;
            //string Time = System.DateTime.Now.ToString();
            return Time;
        }

        void myTimer_DV1(object sender, System.Timers.ElapsedEventArgs e)
        {
            int lChannel = iChannelNum[(int)iSelIndex]; //通道号 Channel number

            CHCNetSDK.NET_DVR_JPEGPARA lpJpegPara = new CHCNetSDK.NET_DVR_JPEGPARA();
            lpJpegPara.wPicQuality = 0; //图像质量 Image quality
            lpJpegPara.wPicSize = 0xff; //抓图分辨率 Picture size: 0xff-Auto(使用当前码流分辨率) 
            //抓图分辨率需要设备支持,更多取值请参考SDK文档
            curTime = GetTimeStamp();
            //JEPG抓图,数据保存在缓冲区中 Capture a JPEG picture and save in the buffer
            uint iBuffSize = 400000; //缓冲区大小需要不小于一张图片数据的大小 The buffer size should not be less than the picture size
            byte[] byJpegPicBuffer = new byte[iBuffSize];
            uint dwSizeReturned = 0;

            if (!CHCNetSDK.NET_DVR_CaptureJPEGPicture_NEW(DV1.m_lUserID, lChannel, ref lpJpegPara, byJpegPicBuffer, iBuffSize, ref dwSizeReturned))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_CaptureJPEGPicture_NEW failed, error code= " + iLastErr;
                MessageBox.Show(str);
                //DebugInfo(str);
                return;
            }
            else
            {
                //将缓冲区里的JPEG图片数据写入文件 save the data into a file
                string str =  DV1.DeviceID + "_" + curTime + ".jpg";
                FileStream fs = new FileStream(savePath1 +"\\" + str, FileMode.Create);
                
                int iLen = (int)dwSizeReturned;
                fs.Write(byJpegPicBuffer, 0, iLen);
                fs.Close();
                //创建txt并写入图片的名字,供上传程序提取名字来找到图片上传
                if (!File.Exists(System.Environment.CurrentDirectory + "\\picName.txt"))
                {

                    FileStream fs1 = new FileStream(System.Environment.CurrentDirectory + "\\picName.txt", FileMode.Create, FileAccess.Write);//创建写入文件 
                    StreamWriter sw = new StreamWriter(fs1);
                    sw.WriteLine(str + "\n");//开始写入值

                    sw.Close();
                    fs1.Close();

                }
                else
                {
                    FileStream fs2 = new FileStream(System.Environment.CurrentDirectory + "\\picName.txt", FileMode.Open, FileAccess.Write);
                    StreamWriter sr = new StreamWriter(fs2);
                    sr.BaseStream.Seek(0, SeekOrigin.End); 
                    sr.WriteLine(str+"\n");//开始写入值
                    sr.Close();
                    fs2.Close();
                }

                str = "NET_DVR_CaptureJPEGPicture_NEW succ and save the data in buffer " + str;
                //DebugInfo(str);
            }
        }
        void myTimer_DV2(object sender, System.Timers.ElapsedEventArgs e)
        {

            int lChannel = iChannelNum[(int)iSelIndex]; //通道号 Channel number

            CHCNetSDK.NET_DVR_JPEGPARA lpJpegPara = new CHCNetSDK.NET_DVR_JPEGPARA();
            lpJpegPara.wPicQuality = 0; //图像质量 Image quality
            lpJpegPara.wPicSize = 0xff; //抓图分辨率 Picture size: 0xff-Auto(使用当前码流分辨率) 
            //抓图分辨率需要设备支持,更多取值请参考SDK文档
            curTime = GetTimeStamp();
            //JEPG抓图,数据保存在缓冲区中 Capture a JPEG picture and save in the buffer
            uint iBuffSize = 400000; //缓冲区大小需要不小于一张图片数据的大小 The buffer size should not be less than the picture size
            byte[] byJpegPicBuffer = new byte[iBuffSize];
            uint dwSizeReturned = 0;

            if (!CHCNetSDK.NET_DVR_CaptureJPEGPicture_NEW(DV2.m_lUserID, lChannel, ref lpJpegPara, byJpegPicBuffer, iBuffSize, ref dwSizeReturned))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_CaptureJPEGPicture_NEW failed, error code= " + iLastErr;
                MessageBox.Show(str);
                //DebugInfo(str);
                return;
            }
            else
            {
                //将缓冲区里的JPEG图片数据写入文件 save the data into a file
                string str = DV2.DeviceID + "_" + curTime + ".jpg";
                FileStream fs = new FileStream(savePath2 + "\\" + str, FileMode.Create);

                int iLen = (int)dwSizeReturned;
                fs.Write(byJpegPicBuffer, 0, iLen);
                fs.Close();
                //创建txt并写入图片的名字,供上传程序提取名字来找到图片上传
                if (!File.Exists(System.Environment.CurrentDirectory + "\\picName.txt"))
                {

                    FileStream fs1 = new FileStream(System.Environment.CurrentDirectory + "\\picName.txt", FileMode.Create, FileAccess.Write);//创建写入文件 
                    StreamWriter sw = new StreamWriter(fs1);
                    sw.WriteLine(str);//开始写入值

                    sw.Close();
                    fs1.Close();

                }
                else
                {
                    FileStream fs2 = new FileStream(System.Environment.CurrentDirectory + "\\picName.txt", FileMode.Open, FileAccess.Write);
                    StreamWriter sr = new StreamWriter(fs2);
                    sr.BaseStream.Seek(0, SeekOrigin.End);
                    sr.WriteLine(str + "\n");//开始写入值
                    sr.Close();
                    fs2.Close();
                }

                str = "NET_DVR_CaptureJPEGPicture_NEW succ and save the data in buffer " + str;
                //DebugInfo(str);
            }
        }
        void myTimer_DV3(object sender, System.Timers.ElapsedEventArgs e)
        {

            int lChannel = iChannelNum[(int)iSelIndex]; //通道号 Channel number

            CHCNetSDK.NET_DVR_JPEGPARA lpJpegPara = new CHCNetSDK.NET_DVR_JPEGPARA();
            lpJpegPara.wPicQuality = 0; //图像质量 Image quality
            lpJpegPara.wPicSize = 0xff; //抓图分辨率 Picture size: 0xff-Auto(使用当前码流分辨率) 
            //抓图分辨率需要设备支持,更多取值请参考SDK文档
            curTime = GetTimeStamp();
            //JEPG抓图,数据保存在缓冲区中 Capture a JPEG picture and save in the buffer
            uint iBuffSize = 400000; //缓冲区大小需要不小于一张图片数据的大小 The buffer size should not be less than the picture size
            byte[] byJpegPicBuffer = new byte[iBuffSize];
            uint dwSizeReturned = 0;

            if (!CHCNetSDK.NET_DVR_CaptureJPEGPicture_NEW(DV3.m_lUserID, lChannel, ref lpJpegPara, byJpegPicBuffer, iBuffSize, ref dwSizeReturned))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                str = "NET_DVR_CaptureJPEGPicture_NEW failed, error code= " + iLastErr;
                MessageBox.Show(str);
                //DebugInfo(str);
                return;
            }
            else
            {
                //将缓冲区里的JPEG图片数据写入文件 save the data into a file
                string str = DV3.DeviceID + "_" + curTime + ".jpg";
                FileStream fs = new FileStream(savePath3 + "\\" + str, FileMode.Create);

                int iLen = (int)dwSizeReturned;
                fs.Write(byJpegPicBuffer, 0, iLen);
                fs.Close();
                //创建txt并写入图片的名字,供上传程序提取名字来找到图片上传
                if (!File.Exists(System.Environment.CurrentDirectory + "\\picName.txt"))
                {

                    FileStream fs1 = new FileStream(System.Environment.CurrentDirectory + "\\picName.txt", FileMode.Create, FileAccess.Write);//创建写入文件 
                    StreamWriter sw = new StreamWriter(fs1);
                    sw.WriteLine(str);//开始写入值

                    sw.Close();
                    fs1.Close();

                }
                else
                {
                    FileStream fs2 = new FileStream(System.Environment.CurrentDirectory + "\\picName.txt", FileMode.Open, FileAccess.Write);
                    StreamWriter sr = new StreamWriter(fs2);
                    sr.BaseStream.Seek(0, SeekOrigin.End);
                    sr.WriteLine(str + "\n");//开始写入值
                    sr.Close();
                    fs2.Close();
                }

                str = "NET_DVR_CaptureJPEGPicture_NEW succ and save the data in buffer " + str;
                //DebugInfo(str);
            }
        }

        private void btnJPEG_Click(object sender, EventArgs e)
        {
            MessageBox.Show("时间设定成功,将在预定时间后开始拍照!");
            switch (comboBoxDevice.SelectedIndex) { 
                case 0:
                    //在设定的路径下创建保存图片的文件夹
                    string fileName1 = DV1.DeviceID;
                    savePath1 = System.Environment.CurrentDirectory + "\\"+fileName1;
                    DV1.picTime = double.Parse(textBoxPicTime.Text);
                    UpdateAppConfig("DV1_PicTime", DV1.picTime.ToString());
                    deviceNum += 1;
                    UpdateAppConfig("DeviceNum", deviceNum.ToString());
                    // Determine whether the directory exists.
                    if (!Directory.Exists(savePath1))
                    {
                        // Create the directory it does not exist.
                        Directory.CreateDirectory(savePath1);
                    }

                    //定时器定时拍摄图片
                    myTimer = new System.Timers.Timer(DV1.picTime * 60000);//定时周期10秒
                    myTimer.Enabled = true; //定时器开始用
                    Control.CheckForIllegalCrossThreadCalls = false;

                    myTimer.Elapsed += myTimer_DV1;//到10秒了做的事件

                    myTimer.AutoReset = true; //是否不断重复定时器操作
                    break;
                case 1:
                    //在设定的路径下创建保存图片的文件夹
                    string fileName2 = DV2.DeviceID;
                    savePath2 = System.Environment.CurrentDirectory + "\\" + fileName2;
                    DV2.picTime = double.Parse(textBoxPicTime.Text);
                    UpdateAppConfig("DV2_PicTime", DV2.picTime.ToString());
                    deviceNum += 1;
                    UpdateAppConfig("DeviceNum", deviceNum.ToString());
                    // Determine whether the directory exists.
                    if (!Directory.Exists(savePath2))
                    {
                        // Create the directory it does not exist.
                        Directory.CreateDirectory(savePath2);
                    }

                    //定时器定时拍摄图片
                    myTimer = new System.Timers.Timer(DV2.picTime * 60000);//定时周期10秒
                    myTimer.Enabled = true; //定时器开始用
                    Control.CheckForIllegalCrossThreadCalls = false;

                    myTimer.Elapsed += myTimer_DV2;//到10秒了做的事件

                    myTimer.AutoReset = true; //是否不断重复定时器操作
                    break;
                case 2:
                    //在设定的路径下创建保存图片的文件夹
                    string fileName3 = DV3.DeviceID;
                    savePath3 = System.Environment.CurrentDirectory + "\\" + fileName3;
                    DV3.picTime = double.Parse(textBoxPicTime.Text);
                    UpdateAppConfig("DV3_PicTime", DV3.picTime.ToString());
                    deviceNum += 1;
                    UpdateAppConfig("DeviceNum", deviceNum.ToString());
                    // Determine whether the directory exists.
                    if (!Directory.Exists(savePath3))
                    {
                        // Create the directory it does not exist.
                        Directory.CreateDirectory(savePath3);
                    }

                    //定时器定时拍摄图片
                    myTimer = new System.Timers.Timer(DV3.picTime * 60000);//定时周期10秒
                    myTimer.Enabled = true; //定时器开始用
                    Control.CheckForIllegalCrossThreadCalls = false;

                    myTimer.Elapsed += myTimer_DV3;//到10秒了做的事件

                    myTimer.AutoReset = true; //是否不断重复定时器操作
                    break;
            }
           
        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            //停止预览
            if (DV1.m_lRealHandle >= 0)
            {
                CHCNetSDK.NET_DVR_StopRealPlay(DV1.m_lRealHandle);
                DV1.m_lRealHandle = -1;
            }
            if (DV2.m_lRealHandle >= 0)
            {
                CHCNetSDK.NET_DVR_StopRealPlay(DV2.m_lRealHandle);
                DV2.m_lRealHandle = -1;
            }
            if (DV3.m_lRealHandle >= 0)
            {
                CHCNetSDK.NET_DVR_StopRealPlay(DV3.m_lRealHandle);
                DV3.m_lRealHandle = -1;
            }

            //注销登录
            if (DV1.m_lUserID >= 0)
            {
                CHCNetSDK.NET_DVR_Logout(DV1.m_lUserID);
                DV1.m_lUserID = -1;
            }
            if (DV2.m_lUserID >= 0)
            {
                CHCNetSDK.NET_DVR_Logout(DV2.m_lUserID);
                DV2.m_lUserID = -1;
            }
            if (DV3.m_lUserID >= 0)
            {
                CHCNetSDK.NET_DVR_Logout(DV3.m_lUserID);
                DV3.m_lUserID = -1;
            }
            CHCNetSDK.NET_DVR_Cleanup();

            Application.Exit();
        }

        private void textBoxUserName_TextChanged(object sender, EventArgs e)
        {

        }
        //private void btnGetToken_Click(object sender, EventArgs e)
        //{
        //    if (m_tokenWrite < 0)
        //    {
        //        if (string.IsNullOrWhiteSpace(textBoxToken.Text))
        //        {
        //            //DebugInfo("token can't be NULL!");
        //            MessageBox.Show("令牌不能为空!");
        //        }
        //        else
        //        {
        //           // m_token = textBoxToken.Text;
        //            btnLogin.Enabled = true;
        //            textBoxIP.Enabled = true;
        //            textBoxPort.Enabled = true;
        //            textBoxUser.Enabled = true;
        //            textBoxPassword.Enabled = true;
        //            //textBoxToken.Enabled = false;
        //            //btnGetToken.Text = "修改";
        //            m_tokenWrite = 1;
        //            UpdateAppConfig("Token", m_token);
        //        }
        //    }
        //    else {
        //        //textBoxToken.Enabled = true;
        //        //btnGetToken.Text = "确定";
        //        m_tokenWrite = -1;
        //    }
        //}

        private void comboBoxSpeed_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void time_keypress(object sender, KeyPressEventArgs e)
        {
            if ((Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //e.Handled = true;
            }
            else if(e.KeyChar==46){

                if (textBoxPicTime.Text.Length <= 0)
                    e.Handled = true;           //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(textBoxPicTime.Text, out oldf);
                    b2 = float.TryParse(textBoxPicTime.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }

            }else{
                e.Handled = true;
                MessageBox.Show("请输入数字!");
                textBoxPicTime.Clear();
            }
        }

        private void comboBoxDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxDevice.SelectedIndex == 0) {
                //textBoxToken.Text = m_token;
                textBoxIP.Text = DV1.IPAddress;
                textBoxPort.Text = DV1.PortNumber.ToString();
                textBoxPicTime.Text = DV1.picTime.ToString();
                isDevice = 1;
                if (DV1.m_lUserID < 0)
                {
                    textBoxIP.Enabled = true;
                    textBoxPort.Enabled = true;
                    textBoxUser.Enabled = true;
                    textBoxPassword.Enabled = true;
                    btnLogin.Text = "登陆并预览";
                }
                else {
                    textBoxIP.Enabled = false;
                    textBoxPort.Enabled = false;
                    textBoxUser.Enabled = false;
                    textBoxPassword.Enabled = false;
                    btnLogin.Text = "退出";
                }
            }
            else if (comboBoxDevice.SelectedIndex == 1)
            {
                //textBoxToken.Text = m_token;
                textBoxIP.Text = DV2.IPAddress;
                textBoxPort.Text = DV2.PortNumber.ToString();
                textBoxPicTime.Text = DV2.picTime.ToString();
                isDevice = 2;
                if (DV2.m_lUserID < 0)
                {
                    textBoxIP.Enabled = true;
                    textBoxPort.Enabled = true;
                    textBoxUser.Enabled = true;
                    textBoxPassword.Enabled = true;
                    btnLogin.Text = "登陆并预览";
                }
                else
                {
                    textBoxIP.Enabled = false;
                    textBoxPort.Enabled = false;
                    textBoxUser.Enabled = false;
                    textBoxPassword.Enabled = false;
                    btnLogin.Text = "退出";
                }
            }
            else if (comboBoxDevice.SelectedIndex == 2)
            {
                //textBoxToken.Text = m_token;
                textBoxIP.Text = DV3.IPAddress;
                textBoxPort.Text = DV3.PortNumber.ToString();
                textBoxPicTime.Text = DV3.picTime.ToString();
                isDevice = 3;
                if (DV3.m_lUserID < 0)
                {
                    textBoxIP.Enabled = true;
                    textBoxPort.Enabled = true;
                    textBoxUser.Enabled = true;
                    textBoxPassword.Enabled = true;
                    btnLogin.Text = "登陆并预览";
                }
                else
                {
                    textBoxIP.Enabled = false;
                    textBoxPort.Enabled = false;
                    textBoxUser.Enabled = false;
                    textBoxPassword.Enabled = false;
                    btnLogin.Text = "退出";
                }
            }
        }
        //更新配置文件
        private static void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = false;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey)
                {
                    isModified = true;
                }
            }

            // Open App.Config of executable  
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // You need to remove the old settings object before you can replace it  
            if (isModified)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            // Add an Application Setting.  
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the changes in App.config file.  
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.  
            ConfigurationManager.RefreshSection("appSettings");
        }

        //PTZ control!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        private void PTZControl_Load(object sender, EventArgs e)
        {
            comboBoxSpeed.SelectedIndex = 3;
            //if (m_lRealHandle > -1)
            //{
            //    checkBoxPreview.Checked = true;
            //}
            //else
            //{
            //    checkBoxPreview.Checked = false;
            //}
        }
        private void PTZControlWithSpeed(int m_lRealHandle, uint direct, uint i) {
            CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, direct, i, (uint)comboBoxSpeed.SelectedIndex + 1);
        }
        //private void PTZControlWithSpeed_Other(int m_lUserID, int direct, int i)
        //{
        //    CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel,direct, i, (int)comboBoxSpeed.SelectedIndex + 1);
        //}

        private void btnLeft_MouseDown(object sender, MouseEventArgs e)
        {
            if (isDevice==1)
            {
                PTZControlWithSpeed(DV1.m_lRealHandle, CHCNetSDK.PAN_LEFT,0);
            }
            else if (isDevice == 2) {
                PTZControlWithSpeed(DV2.m_lRealHandle, CHCNetSDK.PAN_LEFT, 0);
            }
            else if (isDevice == 3)
            {
                PTZControlWithSpeed(DV3.m_lRealHandle, CHCNetSDK.PAN_LEFT, 0);
            }
           
        }

        private void btnLeft_MouseUp(object sender, MouseEventArgs e)
        {
            if (isDevice == 1)
            {
                PTZControlWithSpeed(DV1.m_lRealHandle, CHCNetSDK.PAN_LEFT, 1);
            }
            else if (isDevice == 2)
            {
                PTZControlWithSpeed(DV2.m_lRealHandle, CHCNetSDK.PAN_LEFT, 1);
            }
            else if (isDevice == 3)
            {
                PTZControlWithSpeed(DV3.m_lRealHandle, CHCNetSDK.PAN_LEFT, 1);
            }
        }

        private void textBoxIP_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBoxPassword_TextChanged(object sender, EventArgs e)
        {

        }

        private void RealPlayWnd1_Click(object sender, EventArgs e)  //1号摄像头窗口显示
        {

        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void textBoxPort_TextChanged(object sender, EventArgs e)
        {

        }

        private void RealPlayWnd2_Click(object sender, EventArgs e)
        {

        }

        private void textBoxPicTime_TextChanged(object sender, EventArgs e)
        {

        }

        //以下为控制摄像头转动的功能,暂时设备无此功能
        //private void btnUp_MouseDown(object sender, MouseEventArgs e)
        //{
        //    if (checkBoxPreview.Checked)
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.TILT_UP, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //    else
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.TILT_UP, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //}

        //private void btnUp_MouseUp(object sender, MouseEventArgs e)
        //{
        //    if (checkBoxPreview.Checked)
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.TILT_UP, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //    else
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.TILT_UP, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //}

        //private void btnRight_MouseDown(object sender, MouseEventArgs e)
        //{
        //    if (checkBoxPreview.Checked)
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.PAN_RIGHT, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //    else
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.PAN_RIGHT, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //}

        //private void btnRight_MouseUp(object sender, MouseEventArgs e)
        //{
        //    if (checkBoxPreview.Checked)
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.PAN_RIGHT, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //    else
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.PAN_RIGHT, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //}

        //private void btnDown_MouseDown(object sender, MouseEventArgs e)
        //{
        //    if (checkBoxPreview.Checked)
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.TILT_DOWN, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //    else
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.TILT_DOWN, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //}

        //private void btnDown_MouseUp(object sender, MouseEventArgs e)
        //{
        //    if (checkBoxPreview.Checked)
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.TILT_DOWN, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //    else
        //    {
        //        CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.TILT_DOWN, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //    }
        //}

        //private void btnAuto_Click(object sender, EventArgs e)
        //{
        //    if (checkBoxPreview.Checked)
        //    {
        //        if (!bAuto)
        //        {
        //            CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.PAN_AUTO, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //            btnAuto.Text = "Stop";
        //            bAuto = true;
        //        }
        //        else
        //        {
        //            CHCNetSDK.NET_DVR_PTZControlWithSpeed(m_lRealHandle, CHCNetSDK.PAN_AUTO, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //            btnAuto.Text = "Auto";
        //            bAuto = false;
        //        }
        //    }
        //    else
        //    {
        //        if (!bAuto)
        //        {
        //            CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.PAN_AUTO, 0, (uint)comboBoxSpeed.SelectedIndex + 1);
        //            btnAuto.Text = "Stop";
        //            bAuto = true;
        //        }
        //        else
        //        {
        //            CHCNetSDK.NET_DVR_PTZControlWithSpeed_Other(m_lUserID, m_lChannel, CHCNetSDK.PAN_AUTO, 1, (uint)comboBoxSpeed.SelectedIndex + 1);
        //            btnAuto.Text = "Auto";
        //            bAuto = false;
        //        }
        //    }
        //}

    }
}

 

2019-09-24 21:59:41 workid1888 阅读数 63
  • C#急速入门

    Unity开发,C#绝对是基础中的基础,课程针对纯小白而设计,各种语言细节在课程里均有涉猎,从原理到实战,从底层到算法,你想了解的C#,这里应有尽有,除了讲解,还有练习,你说棒不棒,哈哈,当然如果你是有其他语言基础的同学,课程依然会让你收货满满。来吧,我们进入正题。

    13672 人正在学习 去看看 张建飞

有时,我们需要在C#代码中对多个UVC摄像头进行操作,如何实现呢?

建立基于SharpCamera的项目

首先,请根据之前的一篇博文 点击这里 中的说明,建立基于SharpCamera的摄像头控制项目。关键代码如下:

获取多个Camera实例

CameraMgr可以通过ChooseCamera返回多个Camera实例,每个对应一个摄像头。

//获取第一个
camera1 = cameraMgr.ChooseCamera(0);

//获取第二个
camera2 = cameraMgr.ChooseCamera(1);

执行操作

每个camera对象都可以单独进行控制,比如修改亮度,旋转,修改分辨率等。

案例

[外链图片转存失败(img-Bjy6SmY1-1569465138925)(http://blog.zzsgzn.com/posts/46427/1.jpg)]

下载源码

点击下载源码

2015-12-08 19:00:02 waeceo 阅读数 14840
  • C#急速入门

    Unity开发,C#绝对是基础中的基础,课程针对纯小白而设计,各种语言细节在课程里均有涉猎,从原理到实战,从底层到算法,你想了解的C#,这里应有尽有,除了讲解,还有练习,你说棒不棒,哈哈,当然如果你是有其他语言基础的同学,课程依然会让你收货满满。来吧,我们进入正题。

    13672 人正在学习 去看看 张建飞

硕士研三找完工作后就开始投入紧张忙碌的论文生涯,现在我在忙大论文的工程。前期好多的实验和理论,头都大了,好在通过搞这些东西,收获了不少心得。

写一下在用C#读取摄像头并做处理的Demo心得吧。

如果我们需要读取摄像头,并且还要对其中的某帧图像进行处理,比如说取出其中的某个像素点坐标的对应的像素色彩值,RGB或者灰度值。有以下几种方法:

(1)我们第一个想到的就是使用大名鼎鼎的Opencv。确实Opencv非常好用,但是对于一些对于C++一知半解的人来说,要有界面程序的话还得学Qt,哇,Qt配置Opencv可麻烦了,以前做的时候用过,也配置过,可以说非常麻烦,网上众说纷纭,各种版本的配置,基本上没有一个版本能够不出问题的配置好,还是我参考了各个版本后,自己想出的配置方法,也写在我以前的博客里了,如果需要的话,可以上下捣一捣翻一翻,准能找到。我这一次做为啥不用以前的程序了呢?就是因为我刚把环境卸掉了,不想再装了,所以问题来了,想偷懒,就得有其他办法做。如下的方法(2)

(2)好多人说,opencv也可以配置在C#上啊,对,没错,大牛应该能用的了,搞得动。为什么这么说?我问了一下度娘,她说,你必须学习EmguCV才行啊,说这是microsoft吸取了opencv的精华,而后又加入了很多高级功能之后的版本。高大上啊,然后我又开始搜EmguCV,大概的资料在下面两个链接上:

http://www.opencv.org.cn/forum.php?mod=viewthread&tid=32710
http://wenku.baidu.com/link?url=DIvhesSEe7CjxWPtX2YH-HOVciLereVfNVfd-OSZRlcpCGENlYyRO7wdSlbcqkueLRGlqT-UkswmKOKeMbAN6SrJJJb1sE2ic4ukwrcWvoK

资料很少,用的人也不多,所以,给那些刚涉入程序员行列不久的人一条靠谱的建议:我们在做一个工程的时候,网上一搜,会有很多种办法解决,但是,我们不要随便找一个就开始干,这是蛮干,开始的时候可能还没啥难度,网上的资料也够用,但是越往后做,难度越大,网上的资料可以用的资料就越少了,那就要看你的功底了;所以对于内功修为不够的人,千万不要随便学一门武功,容易走火入魔惊恐!这样做是非常浪费时间的,如果你在公司这么干的话,是会有致命后果的。所以公司的人在做一个工程前,首先都会论证网上的各种技术,做法,选一个比较成熟的技术来做,这样的话,节省时间,而且也不容易出现大的错误。我算是记住了!所以这个方案对于我的工程来说也就pass掉了。
换下一话题,大笑,方法(3)
(3)起初为了完成某个短期的目标就慌不择路的选择了该方法,结果越陷越深啊,幸好,我还有点内功,能够控制住自己,没有走火入魔。很心酸。该方法就是本文主要讲的方法
AVICap;avicap32.dll;
百度一搜avicap的话会有不少的资料,不过有很多资料都是重复的,你copy我的,我copy你的,真正的有几篇写的还可以的,链接如下:

http://blog.chinaunix.net/uid-20594503-id-1619859.html
http://blog.csdn.net/laolei1986/article/details/5730245
还有一些百度文档和博客上的程序,基本上都是一个样的,他们的程序我就不贴了,网上可以搜到的,基本功能就是打开视频,保存bmp格式的图片,录制avi格式的视频并保存;
而我的功能需求是这样的,(1)可以打开视频;(2)能够在视频现实中抓取一帧图片并且把图片转换成bmp格式;(3)分析这帧图片,找出某像素点的RGB值;(4)最后用Graphics绘图把RGB值根据大小画到picbox上,二维图像这样的,横轴是像素数(图片中某一行的第多少个像素点),纵轴是R值;
现把各个功能模块的程序帖上来:
先附上一张图吧:

做完后基本是这个效果,左侧的图片是640*480的,右侧是点击图片中的某一列之后的480个像素点对应的R值,0-255;
程序如下:包括功能(1)和功能(2)的程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Drawing;

namespace Test
{
    class VideoWork
    {
        private const int WM_USER = 0x400;
        private const int WS_CHILD = 0x40000000;
        private const int WS_VISIBLE = 0x10000000;
        private const int WM_CAP_START = WM_USER;
        private const int WM_CAP_STOP = WM_CAP_START + 68;
        private const int WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10;
        private const int WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11;
        private const int WM_CAP_SAVEDIB = WM_CAP_START + 25;//保存文件
        private const int WM_CAP_GRAB_FRAME = WM_CAP_START + 60;
        private const int WM_CAP_SEQUENCE = WM_CAP_START + 62;
        private const int WM_CAP_FILE_SET_CAPTURE_FILEA = WM_CAP_START + 20;//设置捕获文件
        public const int WM_CAP_FILE_GET_CAPTURE_FILE = WM_CAP_START + 21;//获得捕获文件
        private const int WM_CAP_SEQUENCE_NOFILE = WM_CAP_START + 63;
        private const int WM_CAP_SET_OVERLAY = WM_CAP_START + 51;
        private const int WM_CAP_SET_PREVIEW = WM_CAP_START + 50;//50
        private const int WM_CAP_SET_CALLBACK_VIDEOSTREAM = WM_CAP_START + 6;
        private const int WM_CAP_SET_CALLBACK_ERROR = WM_CAP_START + 2;
        private const int WM_CAP_SET_CALLBACK_STATUSA = WM_CAP_START + 3;
        private const int WM_CAP_SET_CALLBACK_FRAME = WM_CAP_START + 5;
        private const int WM_CAP_SET_SCALE = WM_CAP_START + 53;
        private const int WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52;
        //private IntPtr hWndC;
        public static IntPtr hWndC;

        private bool bWorkStart = false;
        private IntPtr mControlPtr;
        private int mWidth;
        private int mHeight;
        private int mLeft;
        private int mTop;
                   /// <summary>
                /// 初始化显示图像
                /// </summary>
                /// <param name= “handle “> 控件的句柄 </param>
                /// <param name= “left “> 开始显示的左边距 </param>
                /// <param name= “top “> 开始显示的上边距 </param>
                /// <param name= “width “> 要显示的宽度 </param>
                /// <param name= “height “> 要显示的长度 </param>
                public VideoWork(IntPtr handle, int left, int top, int width, int height)
                {
                mControlPtr = handle;
                mWidth = width;
                mHeight = height;
                mLeft = left;
                mTop = top;
                }
                [DllImport("avicap32.dll ")]
private static extern IntPtr capCreateCaptureWindowA(byte[] lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, int nID);

                [DllImport("avicap32.dll ")]
                private static extern int capGetVideoFormat(IntPtr hWnd, IntPtr psVideoFormat, int wSize);

                //
                //这里特别注意,因为WinAPI中的long为32位,而C#中的long为64wei,所以需要将lParam该为int
                //
                [DllImport("User32.dll ")]
                private static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

                /// <summary>
                /// 开始显示图像
                /// </summary>
                public void Start()
                {
                    if (bWorkStart)
                        return;

                    bWorkStart = true;
                    byte[] lpszName = new byte[100];

                    hWndC = capCreateCaptureWindowA(lpszName, WS_CHILD | WS_VISIBLE, mLeft, mTop, mWidth, mHeight, mControlPtr, 0);

                    if (hWndC.ToInt32() != 0)
                    {
                        SendMessage(hWndC, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0);
                        SendMessage(hWndC, WM_CAP_SET_CALLBACK_ERROR, 0, 0);
                        SendMessage(hWndC, WM_CAP_SET_CALLBACK_STATUSA, 0, 0);
                        SendMessage(hWndC, WM_CAP_DRIVER_CONNECT, 0, 0);
                        SendMessage(hWndC, WM_CAP_SET_SCALE, 1, 0);//打开预览视频的缩放比例
                        SendMessage(hWndC, WM_CAP_SET_PREVIEWRATE, 66, 0);//66ms,视频刷新频率
                        SendMessage(hWndC, WM_CAP_SET_OVERLAY, 1, 0);//启用叠加 注:据说启用此项可以加快渲染速度    
                        SendMessage(hWndC, WM_CAP_SET_PREVIEW, 1, 0);//设置显示图像启动预览模式 PREVIEW
                    }
                    return;

                }

                /// <summary>
                /// 停止显示
                /// </summary>
                public void Stop()
                {
                    SendMessage(hWndC, WM_CAP_DRIVER_DISCONNECT, 0, 0);
                    bWorkStart = false;
                }

                /// <summary>
                /// 抓图
                /// </summary>
                /// <param name= “path “> 要保存bmp文件的路径 </param>
                public void GrabImage()//string path
                {
                    IntPtr hBmp = Marshal.StringToHGlobalAnsi(@"G:\c.bmp");//正确@"G:\c.bmp"   正确Application.StartupPath+".bmp"
                    SendMessage(hWndC, WM_CAP_SAVEDIB, 0, hBmp.ToInt32());
                }
    }
}
比较简单,因为网上都有,但关键点比较难,就是我没有办法从正在播放的视频中抓取一帧直接保存成bmp格式的图片直接分析,取而代之的方法是,先把其中抓获的一帧图片保存到本地磁盘,然后,另外一个picbox在一个定时器中不停的读取本地磁盘保存的bmp格式的图片,然后再绘图类中,我们在从该picbox中读取bitmap格式的图片,总之绕了一大圈,很费劲,不过总算功能实现了,但是,说实话,我不满意!以上功能再绘图类中,如下:
class Draw
    {
        public static double startPixel = 0;
        public static double endPixel = 480;
        public static double startGray = 0;
        public static double endGray = 255;

        private Graphics glight;//灰度值
        public void draw(PaintEventArgs e, PictureBox pictureBox3)
        {
            glight = e.Graphics;
            Pen p = new Pen(Color.Black, 2);

            //画标题
            Font fii = new Font("Tahoma",15, FontStyle.Regular);
            //以下两个for循环是画网格
            for (int i = 0; i < 6; i++)
            {
                glight.DrawLine(p, 70, i * 102, 550, i * 102);//横轴
            }
            for (int i = 0; i < 6; i++)
            {
                glight.DrawLine(p, 70 + i * 96, 0, 70 + i * 96, 512);
            }
            //画纵坐标
            for (int i = 0; i < 6; i++)
            {
                glight.DrawString((startGray + i * ((endGray - startGray) / 5)).ToString(), fii, new SolidBrush(Color.Red), 20, 505 - i * 102);
            }
            //画横坐标
            for (int i = 0; i < 6; i++)
            {
                glight.DrawString((startPixel + i * ((endPixel - startPixel) / 5)).ToString(), fii, new SolidBrush(Color.Red), 50+ i * 96, 520);
            }

            //画波形图
            double perPixel = 480 / (endPixel - startPixel);//每个点占多少像素
            double perGray = 512 / (endGray - startGray);//每个灰度值占多少像素

            //画点
            Pen point = new Pen(Color.Red, 3);
            Bitmap bmp;
            bmp = (Bitmap)pictureBox3.Image;
            if (bmp == null)
                bmp = new Bitmap(@"G:\c.bmp");

            int begin=0;
            for (double i = 0; i < endPixel - startPixel; i=i+1)
            {
                //bmp.GetPixel(Form1.clickpixel, (int)i);
                begin=Convert.ToInt32(bmp.GetPixel(Form1.clickpixel,(int)(startPixel + i)).R);
                if (begin>= startGray &&begin<= endGray)
                    glight.DrawEllipse(point, 70 + (int)(perPixel * (i + 1)), 512 - (int)((begin - startGray) * perGray), 1, 1);//画椭圆 420 - x * 100, 610 - y * 100, 1, 1
            }
        }
    }
貌似都完成了,但是还有一个令我百思不得其解的问题,以前graphics绘图,刷新的时候就直接在定时器中用invalidate就可以搞定了,一般在定时器中首先调用抓图函数并保存到本地,然后另外一个picturebox在读取本地的图片就OK了,但是该实验这么做就就不行,在获取了图片之后,就直接刷新是不行的,在绘图中会报错,解决方法是在用一个定时器,在另外一个定时器中定时刷新就可以了,如下程序:
    private void timer1_Tick(object sender, EventArgs e)
                {
                    wv.GrabImage();
                    this.pictureBox3.ImageLocation = @"G:\c.bmp";
                }

我 2015/12/8 20:27:13

                private void timer2_Tick(object sender, EventArgs e)
                {
                    this.pictureBox2.Invalidate();//代表每隔多长时间就重绘一次
                }

至此,该工程基本完成了,但是效率很低,因为抓帧后保存本地---picbox从本地读取----bitmap从picbox读取,所以绕了很多弯子,动态显示的时候,鼠标都在抖动,说明很差啊,不过也算是用该方法完成了这个功能了吧,因为我实在不知道该如何从视频中直接抓取一帧bitmap的图像直接处理。有知道的大神,可以写评论啊,谢谢!

2012-12-06 16:03:10 deepleo 阅读数 1940
  • C#急速入门

    Unity开发,C#绝对是基础中的基础,课程针对纯小白而设计,各种语言细节在课程里均有涉猎,从原理到实战,从底层到算法,你想了解的C#,这里应有尽有,除了讲解,还有练习,你说棒不棒,哈哈,当然如果你是有其他语言基础的同学,课程依然会让你收货满满。来吧,我们进入正题。

    13672 人正在学习 去看看 张建飞

二维码的生成和解码,有两个开源项目可以参考:

一个是google的zxing,另外一个是ThroughWork。

zxing做的很全面,支持各种语言和平台,具体不多讲,自己查去。ThroughWork做的比较早,貌似现在没人维护了。

所以选择了zxing。

解码和生成的代码都比较简单,网上的资料也很多。而C#调用摄像头的也很容易找到。

所以就干脆照抄别人的,简单实现了一个生成二维码,调用摄像头实时扫描二维码。

扫描的基本思路是每个10秒截一次屏,并保存为一个bmp格式的图片,然后调用zxing的类库解码,如果解码成功就终止截屏任务。

扫描界面:


最后秀一下我的二维码:

源代码:C#生成二维码、调用摄像头扫描二维码


原文:http://www.deepleo.com/archives/1518

2015-10-22 00:30:02 HK_5788 阅读数 10071
  • C#急速入门

    Unity开发,C#绝对是基础中的基础,课程针对纯小白而设计,各种语言细节在课程里均有涉猎,从原理到实战,从底层到算法,你想了解的C#,这里应有尽有,除了讲解,还有练习,你说棒不棒,哈哈,当然如果你是有其他语言基础的同学,课程依然会让你收货满满。来吧,我们进入正题。

    13672 人正在学习 去看看 张建飞

          今天开始捣鼓C#启动摄像头,之前做过用 C++调用OPENCV库启动摄像头,C#理论上也可以。 但是看了    这篇博文笔记, 顿时脑洞大开,原来可以和摄像头打交道的库有这么多啊。大笑之前,我就直到OPENCV可以办到。惭愧,自己的知识面太窄了 。

           当然,今天的重头戏是  AForge.NET Framework 。

           先来看个我鼓捣出来的一个简单实例吧:


  由于是晚上嘛,光线不太好哦。导致看起来画质不够好。大笑

     功能其实很简单,打开摄像头,捕获每一帧图像

--------- AForge.NET Framework  介绍

             1,简介

                  AForge.NET是一个专门为开发者和研究者基于C#框架设计的,他包括计算机视觉与人工智能,图像处理,神经网络,遗传算法,机器学习,模糊系统,机器人控制等领域。

            2,主要架构

                     这个框架由一系列的类库组成。主要包括有:
                             AForge.Imaging —— 一些日常的图像处理和过滤器
                             AForge.Vision —— 计算机视觉应用类库
                             AForge.Neuro —— 神经网络计算库AForge.Genetic -进化算法编程库
                             AForge.MachineLearning —— 机器学习类库
                            AForge.Robotics —— 提供一些机器人的工具类库
                            AForge.Video —— 一系列的视频处理类库
                            AForge.Fuzzy —— 模糊推理系统类库
                            AForge.Controls—— 图像,三维,图表显示控件

---------------下载

        现在,版本已更新到2.2.5了。

       下载连接:http://www.aforgenet.com/framework/downloads.html


----------------在VS中添加引用

        1,新建一个C#窗口引用程序。在工具箱中拖一个按钮控件 和 一个pictureBox控件。空间位置和大小自定。

         2,添加引用。

         添加的DLL的名称有:

AForge.Video.DirectShow.dll
AForge.Video.dll


------------添加名称空间

using AForge.Video.DirectShow;
using AForge.Video;

------------添加类属性

 

 ///---声明变量
        public FilterInfoCollection USE_Webcams = null;
        public VideoCaptureDevice cam = null;


--------------按钮被单击事件代码

        //---按钮被单击事件
        private void startBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (startBtn.Text == "开始")
                {
                    ///--
                    startBtn.Text = "停止";
                    ///---启动摄像头
                    cam.Start();
                }
                else
                {
                    ///--设置按钮提示字样
                    startBtn.Text = "开始";
                    ///--停止摄像头捕获图像
                    cam.Stop();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

--------窗口的Load函数源码

        //--窗口加载事件
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                ///---实例化对象
                USE_Webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                ///---摄像头数量大于0
                if (USE_Webcams.Count > 0)
                {
                    ///---禁用按钮
                    startBtn.Enabled = true;
                    ///---实例化对象
                    cam = new VideoCaptureDevice(USE_Webcams[0].MonikerString);
                    ///---绑定事件
                    cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
                }
                else
                {
                    ///--没有摄像头
                    startBtn.Enabled = false;
                    ///---提示没有摄像头
                    MessageBox.Show("没有摄像头外设");
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
       这里自定义了一个函数,源码如下:

        ///------自定义函数
        private void Cam_NewFrame(object obj, NewFrameEventArgs eventArgs)
        {
            pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
            ///---throw new NotImplementedException();
        }

---------窗口的FormClosed事件源码


       ///---窗口关闭事件
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (cam != null)
                {
                    ///---关闭摄像头
                    if (cam.IsRunning)
                    {
                        cam.Stop();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

-----编译运行试试


------完整源码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
///---添加名称空间
using AForge.Video.DirectShow;
using AForge.Video;

namespace OS_webcam
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ///---声明变量
        public FilterInfoCollection USE_Webcams = null;
        public VideoCaptureDevice cam = null;


        //---按钮被单击事件
        private void startBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (startBtn.Text == "开始")
                {
                    ///--
                    startBtn.Text = "停止";
                    ///---启动摄像头
                    cam.Start();
                }
                else
                {
                    ///--设置按钮提示字样
                    startBtn.Text = "开始";
                    ///--停止摄像头捕获图像
                    cam.Stop();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //--窗口加载事件
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                ///---实例化对象
                USE_Webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                ///---摄像头数量大于0
                if (USE_Webcams.Count > 0)
                {
                    ///---禁用按钮
                    startBtn.Enabled = true;
                    ///---实例化对象
                    cam = new VideoCaptureDevice(USE_Webcams[0].MonikerString);
                    ///---绑定事件
                    cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
                }
                else
                {
                    ///--没有摄像头
                    startBtn.Enabled = false;
                    ///---提示没有摄像头
                    MessageBox.Show("没有摄像头外设");
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        ///------自定义函数
        private void Cam_NewFrame(object obj, NewFrameEventArgs eventArgs)
        {
            pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
            ///---throw new NotImplementedException();
        }


        ///---窗口关闭事件
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (cam != null)
                {
                    ///---关闭摄像头
                    if (cam.IsRunning)
                    {
                        cam.Stop();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

没有更多推荐了,返回首页