Taking a Picture with a Computer Camera in WPF Using C#

Here's a complete post on how to take a picture with computer cameras in a WPF (Windows Presentation Foundation) application using C#. The post walks through tools, code examples, and steps for creating a functional camera capture feature.

Taking a Picture with a Computer Camera in WPF Using C#

Getting Started

Using a webcam in a WPF application can be extremely useful for apps involving identity verification, video conferencing, or simple photo capture.

In this guide, we'll walk through how to take a pic with webcam or a computer camera in a WPF app using C# and Dynamsoft library.

Downlod Webcam libraries: Click the link to download

Setup Your WPF Project

Create a new WPF Application in Visual Studio:
  1. Open Visual Studio.
  2. Create a new WPF App (.NET Framework) or WPF App (.NET Core).
  3. Name it CapturePhotos.
  4. Take reference of the Webcame libraries
    • Download the libraries from the link given above.
    • Right Click on your project name and navigate to Add >Referance.
    • On the Referenace Manager Window: Go to Browser tab then click on the Browser button./li>
    • The File Dioloagbox will be opended: Go to path of the downloaded libraries (Webcam) and select the files to reference.
    • Click Add
    • Click OK

Take a Picture with Computer Camera

Taking a Picture with a Computer Camera

 

Here I have shared the logice to take a picture with a computer camera or a Webcame written in both XAML and code behing C#. In the code example, I used the following three WPF controls:

  1. 2 Image Controls: For showing live streaming and captured photo
  2. 2 Comobobox Controls: For Listdown attached cameras and camera resolutions.
  3. Button Conntrol: Capture photos on click.

XAML Code
 <Window x:Class="CapturePhotos.MainWindow"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
     mc:Ignorable="d"  
     Title="Photo Capture" Height="500" Width="400" WindowStartupLocation="CenterScreen">  
   <Border CornerRadius="5" BorderThickness="2" BorderBrush="Gray" Margin="5">  
     <Grid Margin="5">  
       <Grid.ColumnDefinitions>  
         <ColumnDefinition Width="*"/>  
         <ColumnDefinition Width="*"/>  
       </Grid.ColumnDefinitions>  
       <Grid.RowDefinitions>  
         <RowDefinition Height="200"/>  
         <RowDefinition Height="20"/>  
         <RowDefinition Height="30"/>  
         <RowDefinition Height="5"/>  
         <RowDefinition Height="150"/>  
       </Grid.RowDefinitions>  
       <GroupBox Margin="5,10" Header="Live Image" Name="gblive">  
         <Image Name="DSViewer" Stretch="Fill"/>  
       </GroupBox>  
       <GroupBox Grid.Column="1" Grid.RowSpan="1" Margin="5,10" Header="Captured Image" Name="gvcapture">  
         <Image x:Name="image1" Stretch="Fill" ></Image>  
       </GroupBox>  
       <TextBlock Text="Select Camera" Grid.Row="1"/>  
       <TextBlock Text="Select Resolution" Grid.Row="1" Grid.Column="1"/>  
       <ComboBox Name="cbxSources" Grid.Row="2" SelectionChanged="cbxSources_SelectionChanged"/>  
       <ComboBox Name="cbxResolution" Grid.Row="2" Grid.Column="1" SelectionChanged="cbxResolution_SelectionChanged"/>  
       <Button Name="btnCapture" IsEnabled="False" Margin="5,2" Width="200" Grid.Row="4" Grid.ColumnSpan="2" Content="Capture" Click="btnCapture_Click"></Button>  
     </Grid>  
   </Border>  
 </Window>  

Code Behind: C#
 using Dynamsoft.Common;  
 using Dynamsoft.Core;  
 using Dynamsoft.UVC;  
 using System;  
 using System.Drawing;  
 using System.Drawing.Imaging;  
 using System.Windows;  
 using System.Windows.Controls;  
 namespace CapturePhotos  
 {  
   /// <summary>  
   /// Interaction logic for MainWindow.xaml  
   /// </summary>  
   public partial class MainWindow : Window  
   {  
     private string m_StrProductKey = "t0078oQAAALS176sNWXF5Io4vXp2khlj+SCbN1ElJvDJhZo7HC0N3UdopMK+K7l9TSzE8mE9arzyR+jVrx7+VblMIP6jGm7nGJsamBgAfnCAB";  
     private ImageCore m_ImageCore = null;  
     private CameraManager m_CameraManager = null;  
     private Camera m_Camera = null;  
     private Window m_ControlWindow;  
     private delegate void RefreshDelegate(System.Windows.Media.Imaging.BitmapImage temp);  
     private RefreshDelegate m_Refresh;  
     public MainWindow()  
     {  
       //InitializeComponent();  
       try  
       {  
         InitializeComponent();  
         m_CameraManager = new CameraManager(m_StrProductKey);  
         cbxSources.Items.Clear();//Clear all cameras  
         if (m_CameraManager.GetCameraNames() != null)  
         {  
           foreach (string temp in m_CameraManager.GetCameraNames())  
           {  
             this.cbxSources.Items.Add(temp);  
           }  
           cbxSources.SelectedIndex = 0;  
         }  
         m_Refresh += new RefreshDelegate(RefreshImage);  
         m_ControlWindow = Window.GetWindow(image1);  
       }  
       catch (Exception exp)  
       {  
         MessageBox.Show(exp.Message);  
       }  
     }  
     private void RefreshImage(System.Windows.Media.Imaging.BitmapImage temp)  
     {  
       try  
       {  
         DSViewer.Source = temp;  
       }  
       catch(Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  
     private void cbxSources_SelectionChanged(object sender, SelectionChangedEventArgs e)  
     {  
       if (m_CameraManager.GetCameraNames() != null)  
       {  
         if (((ComboBox)sender).SelectedIndex >= 0 && ((ComboBox)sender).SelectedIndex < m_CameraManager.GetCameraNames().Count)  
         {  
           m_Camera = m_CameraManager.SelectCamera((short)cbxSources.SelectedIndex);  
           try  
           {  
             m_Camera.Open();  
           }  
           catch (Exception ex)  
           {  
             m_Camera.Close();  
             m_Camera.Open();  
             MessageBox.Show(ex.Message);  
           }  
           m_Camera.OnFrameCaptrue += m_Camera_OnFrameCaptrue;  
           ResizePictureBox();  
           Properties.Settings.Default.Save();  
         }  
         if (m_Camera != null)  
         {  
           cbxResolution.Items.Clear();  
           foreach (CamResolution camR in m_Camera.SupportedResolutions)  
           {  
             cbxResolution.Items.Add(camR.ToString());  
           }  
           cbxResolution.SelectedIndex = 0;  
           ResizePictureBox();  
           this.cbxResolution.IsEnabled = true;  
           this.btnCapture.IsEnabled = true;  
         }  
         else  
         {  
           this.cbxResolution.IsEnabled = false;  
           this.btnCapture.IsEnabled = false;  
         }  
       }  
     }  
     private void m_Camera_OnFrameCaptrue(Bitmap bitmap)  
     {  
       System.Windows.Media.Imaging.BitmapImage m_Frame = new System.Windows.Media.Imaging.BitmapImage();  
       using (var stream = new System.IO.MemoryStream())  
       {  
         bitmap.Save(stream, ImageFormat.Bmp);  
         stream.Seek(0, System.IO.SeekOrigin.Begin);  
         m_Frame.BeginInit();  
         m_Frame.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;  
         m_Frame.StreamSource = stream;  
         m_Frame.EndInit();  
         stream.SetLength(0);  
         stream.Capacity = 0;  
         stream.Dispose();  
       }  
       m_Frame.Freeze();  
       if (m_ControlWindow != null)  
         m_ControlWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle, m_Refresh, m_Frame);  
     }  
     /// <summary>  
     //By KCB ON 31 AUG 2019 for resizeing picture box  
     /// </summary>  
     private void ResizePictureBox()  
     {  
       if (m_Camera != null)  
       {  
         CamResolution camResolution = m_Camera.CurrentResolution;  
         if (camResolution != null && camResolution.Width > 0 && camResolution.Height > 0)  
         {  
           {  
             double iVideoWidth = gvcapture.Width;  
             double iVideoHeight = gvcapture.Width * camResolution.Height / camResolution.Width;  
             if (iVideoHeight < gvcapture.Height)  
             {  
               image1.Margin = new Thickness(0, (gvcapture.Height - iVideoHeight) / 2, 0, 0);  
               image1.Width = iVideoWidth;  
               image1.Height = iVideoHeight;  
             }  
             else  
             {  
               image1.Margin = new Thickness(0, 0, 0, 0);  
               image1.Width = iVideoWidth;  
               image1.Height = iVideoHeight;  
             }  
           }  
         }  
       }  
     }  
     private void cbxResolution_SelectionChanged(object sender, SelectionChangedEventArgs e)  
     {  
       if (cbxResolution.SelectedValue != null)  
       {  
         string[] strWXH = cbxResolution.SelectedValue.ToString().Split(new char[] { ' ' });  
         if (strWXH.Length == 3)  
         {  
           try  
           {  
             m_Camera.CurrentResolution = new CamResolution(int.Parse(strWXH[0]), int.Parse(strWXH[2]));  
           }  
           catch { }  
         }  
         m_Camera.RotateVideo(Dynamsoft.UVC.Enums.EnumVideoRotateType.Rotate_0);  
         ResizePictureBox();  
       }  
     }  
     private void btnCapture_Click(object sender, RoutedEventArgs e)  
     {  
       try  
       {  
         Bitmap temp = m_Camera.GrabImage();  
         image1.Source = DSViewer.Source;  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  
     private void Reset_Click(object sender, RoutedEventArgs e)  
     {  
       try  
       {  
         this.image1.Source = null;  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  
   }  
 }  

How It Works
  1. After the MainWindow is initialized, it will list the attached cameras and their available resolutions in the corresponding combo boxes.
  2. Then, it will start live streaming in the Image control located on the left side using the first camera in the list.
  3. When the user clicks the Capture Button, a frame from the live stream will be extracted and displayed in the Image control located on the right side.

Summary

Capturing photos from a webcam or computer camera in a WPF app is surprisingly straightforward.This approach gives you a solid starting point. I hope this was helpful to you.

Thanks

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال