Esempio n. 1
0
 /// <summary>
 /// 截取一帧图像并保存
 /// </summary>
 /// <param name="filePath">图像保存路径</param>
 /// <param name="fileName">保存的图像文件名</param>
 /// <returns>如果保存成功,则返回完整路径,否则为 null</returns>
 public static string CaptureImage(string filePath, string fileName = null)
 {
     if (sourcePlayer.VideoSource == null)
     {
         return(null);
     }
     if (!Directory.Exists(filePath))
     {
         Directory.CreateDirectory(filePath);
     }
     try
     {
         Image bitmap = sourcePlayer.GetCurrentVideoFrame();
         if (fileName == null)
         {
             fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
         }
         string fullPath = Path.Combine(filePath, fileName + "-cap.jpg");
         bitmap.Save(fullPath, ImageFormat.Jpeg);
         bitmap.Dispose();
         return(fullPath);
     }
     catch (Exception e)
     {
         return(null);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// 截取一帧图像并保存
        /// </summary>
        /// <param name="filePath">图像保存路径</param>
        /// <param name="fileName">保存的图像文件名</param>
        public static string CaptureImage(string filePath, string fileName = null)
        {
            if (sourcePlayer.VideoSource == null)
            {
                return(null);
            }
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            try
            {
                ////sourcePlayer.Start();
                //Image bitmap = sourcePlayer.GetCurrentVideoFrame();
                //if (fileName == null) fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                //bitmap.Save(filePath + @"\" + fileName + "-cap.jpg", ImageFormat.Jpeg);
                //bitmap.Dispose();
                ////sourcePlayer.Stop();



                //IntPtr hbitmap = sourcePlayer.GetCurrentVideoFrame().GetHbitmap();
                //bitmap = System.Drawing.Image.FromHbitmap(hbitmap);
                //fileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpg";
                //img = this.docFolder + "/" + fileName;
                //bmpNew = new Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                //g = Graphics.FromImage(bmpNew);
                //g.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
                //g.Dispose();
                //bitmap.Dispose();

                Image bitmap = sourcePlayer.GetCurrentVideoFrame();


                if (fileName == null)
                {
                    fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                }
                string fullPath = Path.Combine(filePath, fileName + "-cap.jpg");
                bitmap.Save(fullPath, ImageFormat.Jpeg);

                bitmap.Dispose();


                return(fullPath);
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message.ToString());
                MessageBox.Show(e.Message.ToString());
                return(null);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnScannerImage_Click(object sender, EventArgs e)
        {
            if (videoSource == null)
            {
                return;
            }
            bitmap = videoSourcePlayer.GetCurrentVideoFrame();
            string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + ".jpg";

            bitmap.Save(Application.StartupPath + "\\" + fileName, ImageFormat.Jpeg);
            bitmap.Dispose();
        }
Esempio n. 4
0
 private void GetPicture(VideoSourcePlayer videoplayer)
 {
     //try
     {
         if (videoplayer.IsRunning)
         {
             IntPtr       ip           = videoplayer.GetCurrentVideoFrame().GetHbitmap();
             BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                 ip,
                 IntPtr.Zero,
                 Int32Rect.Empty,
                 BitmapSizeOptions.FromEmptyOptions());
             PngBitmapEncoder pE = new PngBitmapEncoder();
             pE.Frames.Add(BitmapFrame.Create(bitmapSource));
             drawDate = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss");
             string picName = GetPath("Image") + "\\" + drawDate + videoplayer.Name + ".jpg";
             if (File.Exists(picName))
             {
                 File.Delete(picName);
             }
             using (Stream stream = File.Create(picName))
             {
                 pE.Save(stream);
             }
             DeleteObject(ip);
             //拍照完成后关摄像头并刷新同时关窗体
             //if (videoSourcePlayer != null && videoSourcePlayer.IsRunning)
             //{
             //    videoSourcePlayer.SignalToStop();
             //    videoSourcePlayer.WaitForStop();
             //}
             // this.Close();
         }
     }
     //catch (Exception ex)
     // {
     //     MessageBox.Show("摄像头异常:" + ex.Message);
     // }
 }
Esempio n. 5
0
        /// <summary>
        /// 截取一帧图像并保存
        /// </summary>
        /// <param name="filePath">图像保存路径</param>
        /// <param name="fileName">保存的图像文件名</param>
        public static string   CaptureImage(string filePath, string fileName = null)
        {
            if (sourcePlayer.VideoSource == null)
            {
                return(null);
            }
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
                return(null);
            }
            try
            {
                //sourcePlayer.Start();
                Image bitmap = sourcePlayer.GetCurrentVideoFrame();
                if (fileName == null)
                {
                    fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                }
                string fullPath = Path.Combine(filePath, fileName + "-cap.jpg");

                //MemoryStream ms = new MemoryStream();
                //bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                //bitmap.Dispose();
                //return ms.ToArray();

                bitmap.Save(fullPath, ImageFormat.Jpeg);
                bitmap.Dispose();
                //sourcePlayer.Stop();
                return(fullPath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
                return(null);
            }
        }
Esempio n. 6
0
        // encender la camara web
        private void button6_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;

            comboBox1.SelectedIndex = 0;

            // conseguir el control de video del form
            VideoSourcePlayer Reproductor = (VideoSourcePlayer)this.panel2.Controls["ControlVideo"];

            Reproductor.VideoSource = new VideoCaptureDevice(this.ColeccionDisp[comboBox1.SelectedIndex].MonikerString);
            Reproductor.Start();

            // verificar que se leea algo
            if (Reproductor.GetCurrentVideoFrame() != null)
            {
                // conseguir la imagen de la  web cam
                Bitmap imagen = new Bitmap(Reproductor.GetCurrentVideoFrame());

                // conseguir el resultado de la lectura
                string[] codigo = BarcodeReader.read(imagen, BarcodeReader.QRCODE);
                MessageBox.Show(codigo.ToString());

                // limpiar la memoria
                imagen.Dispose();

                // agregar cuando se lea algo
                if (codigo != null /*&& codigo.Count() > 0*/)
                {
                    MessageBox.Show(codigo.Length.ToString());
                    //listBox2.Items.Add(codigo[0]);

                    // verificar si existe coincidencia en la base de datos para "codigo"

                    /* crear una nueva conexion */
                    this.conexion = new MySqlConnection(this.cadenaConexion);
                    this.conexion.Open();

                    /* crear un comando */
                    string       nua;
                    string       nombre;
                    string       comandoInterno = "SELECT * FROM estudiante WHERE NUA =";
                    MySqlCommand Comando        = new MySqlCommand(comandoInterno, this.conexion);

                    // conseguir un lector
                    MySqlDataReader lectort = Comando.ExecuteReader();

                    if (lectort.Read())
                    {
                        this.panel2.BackColor = Color.Green;
                    }
                    else
                    {
                        this.panel2.BackColor = Color.Red;
                    }
                }
                else
                {
                    panel3.BackColor = Color.Black;
                }
            }
        }
Esempio n. 7
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            VideoSourcePlayer Reproductor = (VideoSourcePlayer)this.panel2.Controls["ControlVideo"];

            // verificar que se leea algo
            if (Reproductor.GetCurrentVideoFrame() != null)
            {
                // conseguir la imagen de la  web cam
                Bitmap imagen = new Bitmap(Reproductor.GetCurrentVideoFrame());

                // conseguir el resultado de la lectura
                string[] codigo = BarcodeReader.read(imagen, BarcodeReader.QRCODE);

                try
                {
                    // limpiar la memoria
                    imagen.Dispose();

                    // agregar cuando se lea algo
                    if (codigo != null)
                    {
                        char     separador = ' ';
                        string[] matriz    = codigo[0].Split(separador);

                        if (matriz.Count() >= 2)
                        {
                            // verificar si existe coincidencia en la base de datos para "codigo"

                            /* crear una nueva conexion */
                            this.conexion = new MySqlConnection(this.cadenaConexion);
                            this.conexion.Open();

                            /* crear un comando */
                            string nua            = matriz[matriz.Length - 1];
                            string nombre         = matriz[2];
                            string comandoInterno = "SELECT * FROM registro WHERE nua =" + Convert.ToInt32(nua) + ";";



                            MySqlCommand Comando = new MySqlCommand(comandoInterno, this.conexion);

                            // conseguir un lector
                            MySqlDataReader lectort = Comando.ExecuteReader();


                            if (lectort.Read())
                            {
                                this.panel1.BackColor = Color.Green;
                                this.panel1.Refresh();
                                this.label7.Text = this.menAceptado;
                                this.label7.Refresh();
                                System.Threading.Thread.Sleep(500);

                                this.escritorActual.WriteLine(nombre + " | " + nua);


                                ListViewItem itNua = new ListViewItem(lectort.GetString(1));
                                ListViewItem.ListViewSubItem itNom = new ListViewItem.ListViewSubItem(itNua, lectort.GetString(0));


                                itNua.SubItems.Add(itNom);
                                listView1.Items.Add(itNua);

                                // cerrar al escritor en cada escritura
                                this.conexion.Close();

                                return;
                            }

                            else
                            {
                                this.panel1.BackColor = Color.Red;
                                this.panel1.Refresh();
                                this.label7.Text = this.menRechazado;
                                this.label7.Refresh();
                                System.Threading.Thread.Sleep(500);
                            }
                        }
                    }
                    else
                    {
                        this.panel1.BackColor = Color.Black;
                        panel1.Refresh();
                        this.label7.Text = this.menVacio;
                        this.label7.Refresh();
                    }
                }
                catch (Exception ex)
                {
                    this.panel1.BackColor = Color.Yellow;
                    this.label7.Text      = "INVALIDO";
                    panel1.Refresh();
                    this.label7.Refresh();


                    System.Threading.Thread.Sleep(500);
                }
            }
        }
Esempio n. 8
0
 public Bitmap GetFrame()
 {
     return(VideoSourcePlayer.GetCurrentVideoFrame());
 }
Esempio n. 9
0
    // capture webcam
    static void CaptureWebCam(string devicename, int delay, int resid, int number, int wait, string format, string filename)
    {
        // format
        ImageFormat imageformat;

        if (format.ToLower() == "jpg")
        {
            imageformat = ImageFormat.Jpeg;
        }
        else if (format.ToLower() == "png")
        {
            imageformat = ImageFormat.Png;
        }
        else if (format.ToLower() == "bmp")
        {
            imageformat = ImageFormat.Bmp;
        }
        else
        {
            throw new ApplicationException("wrong format");
        }

        // get video devices
        FilterInfoCollection videoInputDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

        if (videoInputDevices.Count == 0)
        {
            throw new ApplicationException("no cameras");
        }

        // list all devices
        int i = 0;

        foreach (FilterInfo device in videoInputDevices)
        {
            Print("{0,3}: {1}\n", i, device.Name);
            ++i;
        }

        // get deviceid
        int deviceid = 0; // default

        if (devicename != null)
        {
            if (IsNumber(devicename))
            {
                deviceid = ToNumber(devicename);
            }
            else
            {
                bool found = false;
                foreach (FilterInfo device in videoInputDevices)
                {
                    if (device.Name.ToLower().Contains(devicename.ToLower()))
                    {
                        found = true; break;
                    }
                    ++deviceid;
                }
                if (!found)
                {
                    throw new ApplicationException("wrong devicename");
                }
            }
        }
        if (deviceid < 0 || deviceid >= videoInputDevices.Count)
        {
            throw new ApplicationException("wrong deviceid");
        }

        // init capture device
        VideoCaptureDevice videoCaptureDevice = new VideoCaptureDevice(videoInputDevices[deviceid].MonikerString);

        if (videoCaptureDevice.VideoCapabilities.Length == 0)
        {
            throw new ApplicationException("no camera resolutions");
        }

        // list all resolutions
        Print("Camera {0} resolutions\n", deviceid);
        i = 0;
        foreach (VideoCapabilities capabilty in videoCaptureDevice.VideoCapabilities)
        {
            Print("{0,3}: {1} x {2}\n", i, capabilty.FrameSize.Width, capabilty.FrameSize.Height);
            ++i;
        }

        // get max resolutionid
        if (resid == Int32.MinValue)
        {
            i = 0;
            Size max = new Size(0, 0);
            foreach (VideoCapabilities capabilty in videoCaptureDevice.VideoCapabilities)
            {
                if (capabilty.FrameSize.Width > max.Width || (capabilty.FrameSize.Width == max.Width && capabilty.FrameSize.Height > max.Height))
                {
                    resid = i; // default
                    max   = capabilty.FrameSize;
                }
                ++i;
            }
        }
        if (resid < 0 || resid >= videoCaptureDevice.VideoCapabilities.Length)
        {
            throw new ApplicationException("wrong resolutionid");
        }
        videoCaptureDevice.VideoResolution = videoCaptureDevice.VideoCapabilities[resid];

        // init player
        VideoSourcePlayer videoSourcePlayer = new VideoSourcePlayer();

        videoSourcePlayer.VideoSource = videoCaptureDevice;
        videoSourcePlayer.Start();

        // waiting for first capture
        Print("waiting [{0} -d{1} -r{2} -n{3} -w{4} -f{5}] ", deviceid, delay, resid, number, wait, format);
        bool captured = false;

        for (i = 0; i < 25; ++i)
        {
            Print(".");
            Thread.Sleep(delay * 1000); // increase delay if image is black
            if (videoCaptureDevice.IsRunning &&
                videoSourcePlayer.IsRunning &&
                videoSourcePlayer.GetCurrentVideoFrame() != null)
            {
                captured = true;
                break;
            }
        }
        if (!captured)
        {
            Print("\n  capture failed, increase delay");
        }
        Print("\n");

        // captures images
        for (i = 0; i < number; ++i)
        {
            Bitmap bitmap = videoSourcePlayer.GetCurrentVideoFrame();
            if (bitmap == null)
            {
                Print("  capture failed\n");
            }
            else
            {
                string filenamefull;
                if (filename == null)
                {
                    filenamefull = "capcam" + deviceid + "-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "." + format.ToLower(); // default
                }
                else
                {
                    string pathname  = Path.GetDirectoryName(filename);
                    string basename  = Path.GetFileNameWithoutExtension(filename);
                    string extension = Path.GetExtension(filename);
                    if (basename == "")
                    {
                        basename = "capcam";
                    }
                    if (extension == "")
                    {
                        extension = format.ToLower();
                    }
                    if (extension[0] == '.')
                    {
                        extension = extension.Substring(1);
                    }
                    if (number > 1)
                    {
                        basename += DateTime.Now.ToString("yyyyMMdd-HHmmss");
                    }
                    filenamefull = Path.Combine(pathname, basename) + "." + extension;
                }
                bitmap.Save(filenamefull, imageformat);
                Print("  {0}\n", filenamefull);
            }
            Thread.Sleep(wait * 1000);
        }

        // cleanup
        videoSourcePlayer.SignalToStop();
        videoSourcePlayer.WaitForStop();
        videoSourcePlayer.VideoSource = null;
        videoCaptureDevice.SignalToStop();
        videoCaptureDevice.WaitForStop();
    }