VB调用摄像头实现拍照

时间:2022-11-01 10:22:25

今天为大家介绍一个vb拍照的方法,该方法简单实用,充分体现出visual basic 的实用性。

该工程由两个窗体form1,form2,一个标准模块module1组成。

其中模块的代码如下(module1):

Option Explicit

Public Const WS_CHILD = &H40000000 '常量声明

Public Const WS_VISIBLE = &H10000000
    
Public Const WM_CAP_START = &H400

Public Const WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10

Public Const WM_CAP_SET_SCALE = WM_CAP_START + 53

Public Const WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52

Public Const WM_CAP_SET_PREVIEW = WM_CAP_START + 50
    
Public Declare Function capCreateCaptureWindowA Lib "avicap32.dll" ( _
          ByVal lpszWindowName As String, _
          ByVal dwStyle As Long, _
          ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Integer, _
          ByVal hWndParent As Long, ByVal nID As Long) As Long '声明两个用于实现拍照功能api函数
    
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Integer, ByVal lParam As Long) As Long
   

Public px As Long, py As Long '定义全局分辨率变量
............................................................

窗体一(form1)添加两个文本框,一个命令按钮,代码如下:

Private Sub Command1_Click()

px = Val(Text1.Text) '读取由用户自定义输入的分辨率参数

py = Val(Text2.Text)

Load Form2

Form2.Visible = True '载入窗体2并设置为显示状态

End Sub
其效果如图1:

VB调用摄像头实现拍照
                                图1
................................................................................................
窗体2(form2)代码如下:
Private Sub Form_Load()
 
 Me.Width = px * Screen.TwipsPerPixelX '设置窗口大小,以适应拍照分辨率
 
 Me.Height = py * Screen.TwipsPerPixelX
 
          '采集
          uwndc = capCreateCaptureWindowA("", WS_VISIBLE Or WS_CHILD, 0, 0, px, py, Me.hWnd, 0)
          '连接
          SendMessage uwndc, WM_CAP_DRIVER_CONNECT, 0, 0
         
          SendMessage uwndc, WM_CAP_SET_SCALE, True, 0
          '刷新
          SendMessage uwndc, WM_CAP_SET_PREVIEWRATE, 40, 0
        
          SendMessage uwndc, WM_CAP_SET_PREVIEW, True, 0
  End Sub

........................................................
以上为一个简单的拍照程序,你可以将截取的图片载入图片框进行后期处理,从而完成你的任务。