winform攝像頭拍照 C#利用攝像頭拍照


這是我的第一篇博文,決定以后每個程序都要記錄下來,方便以后查閱!

本人小菜一名,本程序也是查閱了網上各位前輩的博客和百度知道所整理出來的一個小程序。

第一次寫有點不知道從何寫起,先貼一張程序圖吧。

 

程序功能,導入Excel用戶模板,模板圖如下

通過身份證查找用戶,根據准考證好生成圖片名。

 

 

下面開始進入程序

利用攝像頭拍照需要調用win32的avicap32.dll和user32.dll。

avicap32.dll:Windows NT 4.0  avicap32.dll是Windows API應用程序接口相關模塊,用於對攝像頭和其它視頻硬件進行AⅥ電影和視頻的截取。

user32.dll:user32.dll是Windows用戶界面相關應用程序接口,用於包括Windows處理,基本用戶界面等特性,如創建窗口和發送消息。

 

代碼部分

 

 1  private int hHwnd = 0;
 2         private const int port = 2000;
 3         private DataTable dtExcel;
 4         private string imgName;
 5         public CameraForm()
 6         {
 7             InitializeComponent();
 8         }
 9         public struct videohdr_tag
10         {
11             public byte[] lpData;
12             public int dwBufferLength;
13             public int dwBytesUsed;
14             public int dwTimeCaptured;
15             public int dwUser;
16             public int dwFlags;
17             public int[] dwReserved;
18 
19         }

 

 1  ///   <summary>   
 2         ///   必需的設計器變量。   
 3         ///   </summary>   
 4 
 5         [DllImport("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
 6         public static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID);
 7         [DllImport("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
 8         public static extern bool capGetDriverDescriptionA(short wDriver, [MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszName, int cbName, [MarshalAs(UnmanagedType.VBByRefStr)]   ref   string lpszVer, int cbVer);
 9         [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
10         public static extern bool DestroyWindow(int hndw);
11         [DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
12         public static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)]   object lParam);
13         [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
14         public static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
15         [DllImport("vfw32.dll")]
16         public static extern string capVideoStreamCallback(int hwnd, videohdr_tag videohdr_tag);
17         [DllImport("vicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]


接下來就要開始要調用攝像頭打開

 1         /// <summary>
 2         /// 開啟攝像頭
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void button1_Click(object sender, EventArgs e)
 7         {
 8             if (hHwnd == 0)
 9                 this.OpenCapture();
10             else
11                 MessageBox.Show("攝像頭已經開啟!","提示");
12         }
 1      /// <summary>
 2         /// 打開攝像頭
 3         /// </summary>
 4         private void OpenCapture()
 5         {
 6             int intWidth = this.panel1.Width;
 7             int intHeight = this.panel1.Height;
 8             int intDevice = 0;
 9             string refDevice = intDevice.ToString();
10             //創建視頻窗口並得到句柄
11             hHwnd = CameraForm.capCreateCaptureWindowA(ref   refDevice, 1342177280, 0, 0, 600, 480, this.panel1.Handle.ToInt32(), 0);
12             if (CameraForm.SendMessage(hHwnd, 0x40a, intDevice, 0) > 0)
13             {
14                 CameraForm.SendMessage(this.hHwnd, 0x435, -1, 0);
15                 CameraForm.SendMessage(this.hHwnd, 0x434, 0x42, 0);
16                 CameraForm.SendMessage(this.hHwnd, 0x432, -1, 0);
17                 CameraForm.SetWindowPos(this.hHwnd, 1, 0, 0, intWidth, intHeight, 6);
18             }
19             else
20             {
21                 CameraForm.DestroyWindow(this.hHwnd);
22             }
23         }

capCreateCaptureWindowA的作用是創建一個視頻窗口,攝像頭捕捉到的視頻圖像在此窗口內顯示,函數返回值就是代表此窗口的句柄。

接下來關閉攝像頭

 1         /// <summary>
 2         ///關閉攝像頭
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void button2_Click(object sender, EventArgs e)
 7         {
 8             //停止視頻注銷視頻句柄
 9             CameraForm.SendMessage(this.hHwnd, 0x40b, 0, 0);
10             CameraForm.DestroyWindow(this.hHwnd);
11             hHwnd = 0;
12         }


然后是拍照

 1   /// <summary>
 2         /// 截圖
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void button3_Click(object sender, EventArgs e)
 7         {
 8             if (hHwnd == 0)
 9             {
10                 MessageBox.Show("請先開啟攝像頭!","提示");
11                 return;
12             }
13             Preview dlg = new Preview();
14             try
15             {
16                 CameraForm.SendMessage(this.hHwnd, 0x41e, 0, 0);
17                 IDataObject obj1 = Clipboard.GetDataObject();
18                 if (obj1.GetDataPresent(typeof(Bitmap)))
19                 {
20                     Rectangle rect = new Rectangle(120, 145, 120, 145);
21                     Image image1 = (Image)obj1.GetData(typeof(Bitmap));
22                     Bitmap bit = (Bitmap)image1;
23                     //MessageBox.Show( bit.Height.ToString());
24                     //MessageBox.Show(bit.Width.ToString());
25 
26                     bit = bit.Clone(new Rectangle(121, 0, 397, 480), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
27                     bit = (Bitmap)GetThumbnailImage(bit, 120, 145);
28                     dlg.Img = bit;
29                     dlg.ImgName = imgName;
30                 }
31             }
32             catch
33             {
34             }
35             dlg.ShowDialog();
36         }
 1  /// <summary>
 2         /// 將某個圖像生成指定尺寸的圖像縮放圖
 3         /// </summary>
 4         /// <param name="myBitmap">原圖像</param>
 5         /// <param name="width">新的圖像寬</param>
 6         /// <param name="height">新的圖像高</param>
 7         /// <returns></returns>
 8         private Image GetThumbnailImage(Bitmap myBitmap, int width, int height)
 9         {
10 
11             //生成圖像的縮放圖   
12             Image.GetThumbnailImageAbort myCallback =
13                 new Image.GetThumbnailImageAbort(ThumbnailCallback);
14 
15             Image myThumbnail = myBitmap.GetThumbnailImage(
16                 width, height, myCallback, IntPtr.Zero);
17             //this.pictureBox1.Image = myThumbnail;
18 
19             return myThumbnail;
20         }
21         public bool ThumbnailCallback()
22         {
23             return false;
24         }

 

 

最后是保存截圖

 1  private void button1_Click(object sender, EventArgs e)
 2         {
 3             SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
 4             SaveFileDialog1.FileName = imgName;
 5             SaveFileDialog1.Filter = "Image Files(*.JPG;*.GIF)|*.JPG;*.GIF|All files (*.*)|*.*";
 6             if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
 7             {
 8                 img.Save(SaveFileDialog1.FileName, ImageFormat.Bmp);
 9                 this.Close();
10             }
11         }

 

下面是操作Excel

首先判斷Excel版本

 1  /// <summary>
 2         /// 檢測Excel版本信息
 3         /// </summary>
 4         /// <returns></returns>
 5         public static double JongCheckExcelVer()
 6         {
 7             Type objExcelType = Type.GetTypeFromProgID("Excel.Application");
 8             if (objExcelType == null)
 9             {
10                 return 0;
11             }
12             object objApp = Activator.CreateInstance(objExcelType);
13             if (objApp == null)
14             {
15                 return 0;
16             }
17             object objVer = objApp.GetType().InvokeMember("Version", BindingFlags.GetProperty, null, objApp, null);
18             double iVer = Convert.ToDouble(objVer.ToString());
19             objVer = null;
20             objApp = null;
21             objExcelType = null;
22             GC.Collect();
23             return iVer;
24         }
25 
26         public static String JongGetExcelVerStr()
27         {
28             String s1;
29             double excelver;
30             excelver = JongCheckExcelVer();// ExistsExcelRegedit();
31             s1 = " Office ";
32             if (excelver == 0)
33             {
34                 MessageBox.Show("無法識別Excel的版本", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Information);
35                 s1 = "無法識別 office 版本";
36             }
37             else if (excelver >= 14) s1 += "2010或以上";
38             else if (excelver >= 12) s1 += "2007";
39             else if (excelver >= 11) s1 += "2003";
40             else if (excelver >= 10) s1 += "XP";
41             else if (excelver >= 9) s1 += "2000";
42             else if (excelver >= 8) s1 += "97";
43             else if (excelver >= 7) s1 += "95";
44 
45             return s1;
46         }

 

 接着是導入到DataTable

   /// <summary>
        /// 導入excel到datata
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
            try
            {
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    DataSet ds = new DataSet();

                    string strConn = "";


                    if (JongCheckExcelVer() >= 12)
                    {
                        strConn = "Provider=Microsoft.Ace.OLEDB.12.0;" + "Data Source=" + fd.FileName + ";" + "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                    }
                    else if (JongCheckExcelVer() >= 8)
                    {
                        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fd.FileName + ";" + "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    }
                    else if (JongCheckExcelVer() == 0)
                    {
                        MessageBox.Show("無法識別Excel的版本", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    OleDbConnection conn = new OleDbConnection(strConn);
                    conn.Open();
                    string strExcel = "";
                    //string strSheet = "";
                    string strSheetName = "";
                    OleDbDataAdapter myCommand = null;
                    DataTable dtExcelName = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);

                    strSheetName = dtExcelName.Rows[0][2].ToString();
                    
                    strExcel = string.Format("select * from [{0}$]", "Sheet1"); //Bicycle為excel中工作薄
                    myCommand = new OleDbDataAdapter(strExcel, strConn);
                    myCommand.Fill(ds, "Sheet1");
                    System.Data.DataTable dt = new System.Data.DataTable();
                    dt = ds.Tables[0];
                    dtExcel = dt;
                    MessageBox.Show("導入成功!","提示");
                }
                else
                    MessageBox.Show("導入失敗!","提示");
            }
            catch
            {
                MessageBox.Show("請選擇相應的excel文件", "警告");
            }
        }

 

 

本程序代碼大部分來之互聯網,如有雷同,純屬必然。 可以加群討論,群里有各種源碼,資料: 215269573

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM