Advertisement
FlyFar

Use Windows API to capture a image from a Webcam in Go

Jul 15th, 2023
1,494
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.83 KB | Cybersecurity | 0 0
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "fmt"
  6.     "io"
  7.     "io/ioutil"
  8.     "os"
  9.     "os/exec"
  10.     "syscall"
  11.     "unsafe"
  12.  
  13. )
  14.  
  15. var (
  16.     avicap32   = syscall.NewLazyDLL("avicap32.dll")
  17.     proccapCreateCaptureWindowA  = avicap32.NewProc("capCreateCaptureWindowA")
  18.    
  19.     user32  = syscall.NewLazyDLL("user32.dll")
  20.     procSendMessageA = user32.NewProc("SendMessageA")
  21. )
  22.  
  23. func CaptureWebcam() {
  24.     var name = "WebcamCapture"
  25.     handle, _, _ := proccapCreateCaptureWindowA.Call(uintptr(unsafe.Pointer(&name)), 0, 0, 0, 320, 240, 0, 0)
  26.     procSendMessageA.Call(handle, 0x40A, 0, 0) //WM_CAP_DRIVER_CONNECT
  27.     procSendMessageA.Call(handle, 0x432, 30, 0) //WM_CAP_SET_PREVIEW
  28.     procSendMessageA.Call(handle, 0x43C, 0, 0) //WM_CAP_GRAB_FRAME
  29.     procSendMessageA.Call(handle, 0x41E, 0, 0) //WM_CAP_EDIT_COPY
  30.     procSendMessageA.Call(handle, 0x40B, 0, 0) //WM_CAP_DRIVER_DISCONNECT
  31.     camera, err := os.Create("Image.png")
  32.     if err != nil {
  33.     fmt.Println(err)
  34.         return
  35.     }
  36.     clip, err := readClipboard()
  37.     if err != nil {
  38.     fmt.Println(err)
  39.         return
  40.     }
  41.     _, err = io.Copy(camera, clip)
  42.     if err != nil {
  43.     fmt.Println(err)
  44.         return
  45.     }
  46.     camera.Close()
  47. }
  48.  
  49. func readClipboard() (io.Reader, error) {
  50.     f, err := ioutil.TempFile("", "")
  51.     if err != nil {
  52.     fmt.Println(err)
  53.         return nil, err
  54.     }
  55.     f.Close()
  56.     _, err = exec.Command("PowerShell", "-Command", "Add-Type", "-AssemblyName", fmt.Sprintf("System.Windows.Forms;$clip=[Windows.Forms.Clipboard]::GetImage();if ($clip -ne $null) { $clip.Save('%s') };", f.Name())).CombinedOutput()
  57.     if err != nil {
  58.     fmt.Println(err)
  59.         return nil, err
  60.     }
  61.     r := new(bytes.Buffer)
  62.     file, err := os.Open(f.Name())
  63.     if err != nil {
  64.     fmt.Println(err)
  65.         return nil, err
  66.     }
  67.     if _, err := io.Copy(r, file); err != nil {
  68.     fmt.Println(err)
  69.         return nil, err
  70.     }
  71.     file.Close()
  72.     os.Remove(f.Name())
  73.     return r, nil
  74. }
  75.  
  76. func main() {
  77.     CaptureWebcam()
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement