In many software systems, users are allowed to set their own portraits. They can even use cameras to take photos of their portraits, just like QQ's self-timer portraits.
How is this function implemented? Most directly, we can use the VFW technology or DirectX technology provided by Windows to capture videos and images captured by cameras. However, no matter which of the two technologies is used, it is not so easy to implement a camera function that is compatible with all cameras and runs stably. Fortunately, OMCS has a built-in WinForm control that integrates this function.PhotoPanel,We can use it directly.
The main interfaces of the PhotoPanel control are shown in:
/// <Summary> /// initialize the camera and start it. /// </Summary> void Start (); /// <summary> // stop the camera. /// </Summary> void Stop (); /// <summary> /// take a photo. Returns the current frame. /// </Summary> Bitmap GetCurrentImage ();
Drag the PhotoPanel control from the toolbox to your UI, call its Start method, initialize the camera, and Start it. Then, the PhotoPanel control surface will draw the video captured by the camera.
When taking a photo, call the GetCurrentImage method to get the current frame and save it as a bitmap.
After the photo is taken, call the Stop method to Stop and release the camera device.
There are two other problems:
(1) How do I set the index of the camera to be used? This can be specified through the CameraIndex attribute exposed by the PhotoPanel control.
(2) how to set the Photo size? The Photo size is the PhotoPanel size. The default value is 160*120. Of course, this size is not arbitrary. It must be the resolution supported by the current camera. For example, cameras support 160*120, 320*240, and 640*480.
OK. Now we have written a demo that uses PhotoPanel to implement the selfie Avatar function. The main code of the demo is as follows:
Public partial class TakePhotoForm: Form {public TakePhotoForm () {InitializeComponent (); this. photoPanel1.CameraIndex = 0; // set the camera this. photoPanel1.Start (); // start the camera} private Bitmap photo = null; /// <summary> /// photograph result /// </summary> public Bitmap Photo {get {return photo;} set {photo = value ;}} // take a photo private void button#click (object sender, EventArgs e) {this. photo = this. photoPanel1.GetCurrentImage (); this. photoPanel1.Stop (); this. dialogResult = System. windows. forms. dialogResult. OK;} private void TakePhotoForm_FormClosing (object sender, FormClosingEventArgs e) {this. photoPanel1.Stop ();}}
Shows the running effect:
Download the demo source code.