C# 视频拍照程序
各位大虾好:我有个视频拍照程序,电脑连接摄像头后,调试没错,点击"打开视频",只出现一个黑框,和不连接摄像头点击按钮的反映是一样的。
//VideoWork.cs
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
namespace ctia
{
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;
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;
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;
private bool bWorkStart = false;
private IntPtr mControlPtr;
private int mWidth;
private int mHeight;
private int mLeft;
private int mTop;
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 );
[DllImport("User32.dll")]
private static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);
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);
SendMessage(hWndC, WM_CAP_SET_OVERLAY, 1, 0);
SendMessage(hWndC, WM_CAP_SET_PREVIEW, 1,0);
}
return;
}
}
//form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace ctia
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)//打开视频
{
VideoWork vw = new VideoWork(this.pictureBox1.Handle, this.pictureBox1.Left, this.pictureBox1.Top, this.pictureBox1.Width, this.pictureBox1.Height);
vw.Start();
}
}
}
//program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ctia
{
static class Program
{
static void Main()
{
Application.Run(new Form1());
}
}
} --------------------编程问答-------------------- up --------------------编程问答-------------------- 不好做。。。 --------------------编程问答-------------------- 却确实不好做啊!~ --------------------编程问答-------------------- 楼上的回答太不负责了吧,很多高人都应该做过吧。 --------------------编程问答-------------------- 程序里的SendMessage函数发送消息,这部分有问题吧,没有消息实现过程? --------------------编程问答-------------------- 最烦的就是和硬件打交道! --------------------编程问答-------------------- 挺厉害的吗 --------------------编程问答-------------------- 期待牛人出现。。。 --------------------编程问答-------------------- VFW视频编程问题比较多,建议用DirectShow。下面的网页提供C#的视频采集源码,而且兼容性、稳定性都很好。
http://www.codeproject.com/KB/directx/directxcapture.aspx --------------------编程问答-------------------- 不会啦 学习中1·· --------------------编程问答-------------------- MARK --------------------编程问答-------------------- 看不懂。 --------------------编程问答--------------------
支持。楼主的问题我也曾经发贴问过,也是黑黑的一片,就是不显示图像。
现在只好用 DShowNET.dll 了。
--------------------编程问答-------------------- http://topic.csdn.net/u/20091202/12/e485aa77-df7e-4026-b46e-e4b63feca911.html --------------------编程问答-------------------- 这个问题我也碰到过,帮顶... --------------------编程问答--------------------
public class VedioGrap
{
private static int hHwnd;
//private const int port = 2000;
private struct videohdr_tag
{
//private byte[] lpData;
//private int dwBufferLength;
//private int dwBytesUsed;
//private int dwTimeCaptured;
//private int dwUser;
//private int dwFlags;
//private int[] dwReserved;
}
private delegate bool CallBack (int hwnd, int lParam);
[DllImport ("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int capCreateCaptureWindowA ([MarshalAs (UnmanagedType.VBByRefStr)] ref string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID);
[DllImport ("avicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern bool capGetDriverDescriptionA (short wDriver, [MarshalAs (UnmanagedType.VBByRefStr)] ref string lpszName, int cbName, [MarshalAs (UnmanagedType.VBByRefStr)] ref string lpszVer, int cbVer);
[DllImport ("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern bool DestroyWindow (int hndw);
[DllImport ("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int SendMessage (int hwnd, int wMsg, int wParam, [MarshalAs (UnmanagedType.AsAny)] object lParam);
[DllImport ("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int SetWindowPos (int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
[DllImport ("vfw32.dll")]
private static extern string capVideoStreamCallback (int hwnd, videohdr_tag videohdr_tag);
[DllImport ("vicap32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern bool capSetCallbackOnFrame (int hwnd, string s);
/// <summary>
/// 开始载入视频
/// </summary>
public bool OpenCapture (Panel pnlVideo)
{
bool videostart = false;
int intWidth = pnlVideo.Width;
int intHeight = pnlVideo.Height;
int intDevice = 0;
string refDevice = intDevice.ToString ();
//创建视频窗口并得到句柄
hHwnd = VedioGrap.capCreateCaptureWindowA (ref refDevice, 1342177280, 0, 0, 640, 480, pnlVideo.Handle.ToInt32 (), 0);
if (SendMessage (hHwnd, 0x40a, intDevice, 0) > 0)
{
SendMessage (hHwnd, 0x435, -1, 0);
SendMessage (hHwnd, 0x434, 0x01, 0);
SendMessage (hHwnd, 0x432, -1, 0);
SetWindowPos (hHwnd, 1, 0, 0, intWidth, intHeight, 6);
videostart = true;
}
else
{
VedioGrap.DestroyWindow (hHwnd);
videostart = false;
MessageBox.Show ("加载视频失败,请检查是否有安装设备!", "拍照");
}
return videostart;
}
/// <summary>
/// 停止视频
/// </summary>
public void StopVideo ()
{
//停止视频注销视频句柄
SendMessage (hHwnd, 0x40b, 0, 0);
DestroyWindow (hHwnd);
}
/// <summary>
/// 截图
/// </summary>
/// <returns></returns>
public Image GrapPhoto ()
{
Image photo = null;
SendMessage (hHwnd, 0x41e, 0, 0);
IDataObject obj1 = Clipboard.GetDataObject ();
if (obj1.GetDataPresent (typeof (Bitmap)))
{
photo = (Image)obj1.GetData (typeof (Bitmap));
//截完图不能关闭视频,否则无法继续截图
//StopVideo();
}
return photo;
}
}
VedioGrap vedioOperator = new VedioGrap (); //实例化视频类
videostart = vedioOperator.OpenCapture (pnlVideo); //打开视频
pbTakePhoto.Image = vedioOperator.GrapPhoto (); //拍照
vedioOperator.StopVideo (); Clipboard.Clear (); //关闭移除剪贴板数据,防止再次加载时保留上次头像
--------------------编程问答-------------------- 大家可以看我的,不是黑黑的一片,呵呵~
http://topic.csdn.net/u/20100511/15/3a983b36-a3a0-4561-82df-dfd4c6f3c07e.html --------------------编程问答--------------------
底层操作类:--------------------编程问答--------------------
using System;
using System.Runtime.InteropServices;
namespace GetPhoto
{
/// <summary>
/// AviCapture 的摘要说明。
/// </summary>
public class showVideo
{
//通过调用acicap32.dll进行读取摄像头数据
[DllImport("avicap32.dll")]
public static extern IntPtr capCreateCaptureWindowA(byte[] lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, int nID);
[DllImport("avicap32.dll")]
public static extern bool capGetDriverDescriptionA(short wDriver, byte[] lpszName, int cbName, byte[] lpszVer, int cbVer);
[DllImport("User32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int wMsg, bool wParam, int lParam);
[DllImport("User32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int wMsg, short wParam, int lParam);
[DllImport("User32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int wMsg, short wParam, FrameEventHandler lParam);
[DllImport("User32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, ref BITMAPINFO lParam);
[DllImport("User32.dll")]
public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, ref CAPDRIVERCAPS lParam);
[DllImport("User32.dll")]
public static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
[DllImport("avicap32.dll")]
public static extern int capGetVideoFormat(IntPtr hWnd, IntPtr psVideoFormat, int wSize);
//部分常量
public const int WM_USER = 0x400;
public const int WS_CHILD = 0x40000000;
public const int WS_VISIBLE = 0x10000000;
public const int SWP_NOMOVE = 0x2;
public const int SWP_NOZORDER = 0x4;
public const int WM_CAP_DRIVER_CONNECT = WM_USER + 10;
public const int WM_CAP_DRIVER_DISCONNECT = WM_USER + 11;
public const int WM_CAP_SET_CALLBACK_FRAME = WM_USER + 5;
public const int WM_CAP_SET_PREVIEW = WM_USER + 50;
public const int WM_CAP_SET_PREVIEWRATE = WM_USER + 52;
public const int WM_CAP_SET_VIDEOFORMAT = WM_USER + 45;
public const int WM_CAP_SAVEDIB = WM_USER + 25;
public const int WM_CAP_SET_OVERLAY = WM_USER + 51;
public const int WM_CAP_GET_CAPS = WM_USER + 14;
public const int WM_CAP_DLG_VIDEOFORMAT = WM_USER + 41;
public const int WM_CAP_DLG_VIDEOSOURCE = WM_USER + 42;
public const int WM_CAP_DLG_VIDEODISPLAY = WM_USER + 43;
public const int WM_CAP_EDIT_COPY = WM_USER + 30;
public const int WM_CAP_SET_SEQUENCE_SETUP = WM_USER + 64;
public const int WM_CAP_GET_SEQUENCE_SETUP = WM_USER + 65;
// 结构
[StructLayout(LayoutKind.Sequential)]
//VideoHdr
public struct VIDEOHDR
{
[MarshalAs(UnmanagedType.I4)]
public int lpData;
[MarshalAs(UnmanagedType.I4)]
public int dwBufferLength;
[MarshalAs(UnmanagedType.I4)]
public int dwBytesUsed;
[MarshalAs(UnmanagedType.I4)]
public int dwTimeCaptured;
[MarshalAs(UnmanagedType.I4)]
public int dwUser;
[MarshalAs(UnmanagedType.I4)]
public int dwFlags;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public int[] dwReserved;
}
[StructLayout(LayoutKind.Sequential)]
//BitmapInfoHeader
public struct BITMAPINFOHEADER
{
[MarshalAs(UnmanagedType.I4)]
public Int32 biSize;
[MarshalAs(UnmanagedType.I4)]
public Int32 biWidth;
[MarshalAs(UnmanagedType.I4)]
public Int32 biHeight;
[MarshalAs(UnmanagedType.I2)]
public short biPlanes;
[MarshalAs(UnmanagedType.I2)]
public short biBitCount;
[MarshalAs(UnmanagedType.I4)]
public Int32 biCompression;
[MarshalAs(UnmanagedType.I4)]
public Int32 biSizeImage;
[MarshalAs(UnmanagedType.I4)]
public Int32 biXPelsPerMeter;
[MarshalAs(UnmanagedType.I4)]
public Int32 biYPelsPerMeter;
[MarshalAs(UnmanagedType.I4)]
public Int32 biClrUsed;
[MarshalAs(UnmanagedType.I4)]
public Int32 biClrImportant;
}
[StructLayout(LayoutKind.Sequential)]
//BitmapInfo
public struct BITMAPINFO
{
[MarshalAs(UnmanagedType.Struct, SizeConst = 40)]
public BITMAPINFOHEADER bmiHeader;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
public Int32[] bmiColors;
}
[StructLayout(LayoutKind.Sequential)]
public struct CAPDRIVERCAPS
{
[MarshalAs(UnmanagedType.U2)]
public UInt16 wDeviceIndex;
[MarshalAs(UnmanagedType.Bool)]
public bool fHasOverlay;
[MarshalAs(UnmanagedType.Bool)]
public bool fHasDlgVideoSource;
[MarshalAs(UnmanagedType.Bool)]
public bool fHasDlgVideoFormat;
[MarshalAs(UnmanagedType.Bool)]
public bool fHasDlgVideoDisplay;
[MarshalAs(UnmanagedType.Bool)]
public bool fCaptureInitialized;
[MarshalAs(UnmanagedType.Bool)]
public bool fDriverSuppliesPalettes;
[MarshalAs(UnmanagedType.I4)]
public int hVideoIn;
[MarshalAs(UnmanagedType.I4)]
public int hVideoOut;
[MarshalAs(UnmanagedType.I4)]
public int hVideoExtIn;
[MarshalAs(UnmanagedType.I4)]
public int hVideoExtOut;
}
public delegate void FrameEventHandler(IntPtr lwnd, IntPtr lpVHdr);
// 公共函数
public static object GetStructure(IntPtr ptr, ValueType structure)
{
return Marshal.PtrToStructure(ptr, structure.GetType());
}
public static object GetStructure(int ptr, ValueType structure)
{
return GetStructure(new IntPtr(ptr), structure);
}
public static void Copy(IntPtr ptr, byte[] data)
{
Marshal.Copy(ptr, data, 0, data.Length);
}
public static void Copy(int ptr, byte[] data)
{
Copy(new IntPtr(ptr), data);
}
public static int SizeOf(object structure)
{
return Marshal.SizeOf(structure);
}
}
}
功能操作类:--------------------编程问答-------------------- 一大堆的代码!都快把人压死了! --------------------编程问答-------------------- 留个记号, --------------------编程问答-------------------- 看下win的资料吧 也许会管用~~!这个对笔记本的摄像头操作没一点问题 测试验证过~ --------------------编程问答-------------------- 但怎麼把截到的圖轉換為jpg格式呢?如果不轉換的話,圖片太大,有900K,我用轉換工具轉換為jpg時才11K!整整少了90倍啊!!求助.
using System;
using System.Runtime.InteropServices;
namespace GetPhoto
{
/// <summary>
/// Camera 的摘要说明。
/// </summary>
public class WebCamera
{
private IntPtr lwndC;
private IntPtr mControlPtr;
private int mWidth;
private int mHeight;
// 构造函数
public WebCamera(IntPtr handle, int width, int height)
{
mControlPtr = handle;
mWidth = width;
mHeight = height;
}
// 帧回调的委托
public delegate void RecievedFrameEventHandler(byte[] data);
public event RecievedFrameEventHandler RecievedFrame;
private showVideo.FrameEventHandler mFrameEventHandler;
// 关闭摄像头
public void CloseWebcam()
{
this.capDriverDisconnect(this.lwndC);
}
// 开启摄像头
public bool StartWebCam()
{
byte[] lpszName = new byte[100];
byte[] lpszVer = new byte[100];
try
{
showVideo.capGetDriverDescriptionA(0, lpszName, 100, lpszVer, 100);
this.lwndC = showVideo.capCreateCaptureWindowA(lpszName, showVideo.WS_VISIBLE + showVideo.WS_CHILD, 0, 0, mWidth, mHeight, mControlPtr, 0);
if (this.capDriverConnect(this.lwndC, 0))
{
this.capPreviewRate(this.lwndC, 66);
this.capPreview(this.lwndC, true);
this.capOverlay(this.lwndC, true);
showVideo.BITMAPINFO bitmapinfo = new showVideo.BITMAPINFO();
bitmapinfo.bmiHeader.biSize = showVideo.SizeOf(bitmapinfo.bmiHeader);
bitmapinfo.bmiHeader.biWidth = this.mWidth;
bitmapinfo.bmiHeader.biHeight = this.mHeight;
bitmapinfo.bmiHeader.biPlanes = 1;
bitmapinfo.bmiHeader.biBitCount = 24;
this.capSetVideoFormat(this.lwndC, ref bitmapinfo, showVideo.SizeOf(bitmapinfo));
this.mFrameEventHandler = new showVideo.FrameEventHandler(FrameCallBack);
this.capSetCallbackOnFrame(this.lwndC, this.mFrameEventHandler);
showVideo.SetWindowPos(this.lwndC, 0, 0, 0, mWidth, mHeight, 6);
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
public void grabImage(string path) //抓图到文件
{
IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
showVideo.SendMessage(lwndC, showVideo.WM_CAP_SAVEDIB, 0, hBmp.ToInt32());
}
public void setCaptureSource() //弹出色彩设置对话框
{
showVideo.CAPDRIVERCAPS caps = new showVideo.CAPDRIVERCAPS();
showVideo.SendMessage(lwndC, showVideo.WM_CAP_GET_CAPS, showVideo.SizeOf(caps), ref caps);
if (caps.fHasDlgVideoSource)
{
showVideo.SendMessage(lwndC, showVideo.WM_CAP_DLG_VIDEOSOURCE, 0, 0);
}
}
public void setCaptureFormat() //弹出视频格式设置对话框
{
showVideo.CAPDRIVERCAPS caps = new showVideo.CAPDRIVERCAPS();
showVideo.SendMessage(lwndC, showVideo.WM_CAP_GET_CAPS, showVideo.SizeOf(caps), ref caps);
if (caps.fHasDlgVideoSource)
{
showVideo.SendMessage(lwndC, showVideo.WM_CAP_DLG_VIDEOFORMAT, 0, 0);
}
}
public bool copyToClipBoard() //抓图到剪切板
{
return showVideo.SendMessage(lwndC, showVideo.WM_CAP_EDIT_COPY, 0, 0);
}
// 以下为私有函数
private bool capDriverConnect(IntPtr lwnd, short i)
{
return showVideo.SendMessage(lwnd, showVideo.WM_CAP_DRIVER_CONNECT, i, 0);
}
private bool capDriverDisconnect(IntPtr lwnd)
{
return showVideo.SendMessage(lwnd, showVideo.WM_CAP_DRIVER_DISCONNECT, 0, 0);
}
private bool capPreview(IntPtr lwnd, bool f)
{
return showVideo.SendMessage(lwnd, showVideo.WM_CAP_SET_PREVIEW, f, 0);
}
private bool capPreviewRate(IntPtr lwnd, short wMS)
{
return showVideo.SendMessage(lwnd, showVideo.WM_CAP_SET_PREVIEWRATE, wMS, 0);
}
private bool capSetCallbackOnFrame(IntPtr lwnd, showVideo.FrameEventHandler lpProc)
{
return showVideo.SendMessage(lwnd, showVideo.WM_CAP_SET_CALLBACK_FRAME, 0, lpProc);
}
private bool capSetVideoFormat(IntPtr hCapWnd, ref showVideo.BITMAPINFO BmpFormat, int CapFormatSize)
{
return showVideo.SendMessage(hCapWnd, showVideo.WM_CAP_SET_VIDEOFORMAT, CapFormatSize, ref BmpFormat);
}
private void FrameCallBack(IntPtr lwnd, IntPtr lpVHdr)
{
showVideo.VIDEOHDR videoHeader = new showVideo.VIDEOHDR();
byte[] VideoData;
videoHeader = (showVideo.VIDEOHDR)showVideo.GetStructure(lpVHdr, videoHeader);
VideoData = new byte[videoHeader.dwBytesUsed];
showVideo.Copy(videoHeader.lpData, VideoData);
if (this.RecievedFrame != null)
this.RecievedFrame(VideoData);
}
private bool capOverlay(IntPtr lwnd, bool f)
{
return showVideo.SendMessage(lwnd, showVideo.WM_CAP_SET_OVERLAY, f, 0);
}
}
}
补充:.NET技术 , C#