WPF摄像头使用(WPFMediaKit)

添加WPFMediaKit引用

使用WPFMediaKit操作摄像头需要安装WPFMediaKit相关的Nuget包。选中需要进行摄像头操作的项目,然后通过Nuget安装即可。

页面代码

引入命名空间
在页面XAML代码中添加WPFMediaKit的命名空间:
xmlns:WPFMediaKit="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit"

添加摄像头

<WPFMediaKit:VideoCaptureElement Name="vce" Stretch="Fill" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Grid.ColumnSpan="3" />

详细代码
如下:
CameraWindow.xaml

<Window x:Class="WPF_WPFMediaKit.CameraWindow" x:Name="cameraWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:WPFMediaKit="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit"
        Title="相机" Height="500" Width="765" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="150"/>
        </Grid.ColumnDefinitions>

        <WPFMediaKit:VideoCaptureElement Name="vce" Stretch="Fill" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Grid.ColumnSpan="3" />
        <Button x:Name="btnExChange" Grid.Column="0" Grid.Row="0" Content="切换" Click="btnExChange_Click"></Button>
        <Grid Grid.Column="2" Grid.Row="0" Grid.RowSpan="2">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Button Grid.Row="0" x:Name="btnConfirm" Content="确认" Click="btnConfirm_Click" Visibility="Hidden"></Button>
            <Button Grid.Row="1" x:Name="btnCapture" Content="拍照" Click="btnCapture_Click"></Button>
            <Button Grid.Row="2" x:Name="btnReStart" Content="重拍" Click="btnReStart_Click" Visibility="Hidden"></Button>
        </Grid>
    </Grid>
</Window>

页面交互

设置启动摄像头

vce.VideoCaptureSource = MultimediaUtil.VideoInputNames[cameraIndex];

完成拍照并保存为图片

RenderTargetBitmap bmp = new RenderTargetBitmap((int)vce.ActualWidth, (int)vce.ActualHeight, 96, 96, PixelFormats.Default);

                vce.Measure(vce.RenderSize);
                vce.Arrange(new Rect(vce.RenderSize));
                bmp.Render(vce);
                BitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));

重启摄像头

vce.Play();

详细代码
如下:
CameraWindow.xaml.cs

using System;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using WPFMediaKit.DirectShow.Controls;

namespace WPF_WPFMediaKit
{
    /// <summary>
    /// CameraWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CameraWindow : Window
    {
        private int cameraIndex = 0;  //记录当前选择的摄像头的索引值
        private string imgTempPath = "";

        /// <summary>
        /// 测试用
        /// </summary>
        public CameraWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (MultimediaUtil.VideoInputNames.Length > 0)
            {
                cameraIndex = 0;
                vce.VideoCaptureSource = MultimediaUtil.VideoInputNames[cameraIndex];

                if (MultimediaUtil.VideoInputNames.Length > 1)
                {
                    btnExChange.Visibility = Visibility.Visible;
                }
                else
                {
                    btnExChange.Visibility = Visibility.Hidden;
                }
            }
            else
            {
                MessageBox.Show("当前设备没有安装任何可用摄像头");
                this.Close();
            }
        }

        private void btnCapture_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                RenderTargetBitmap bmp = new RenderTargetBitmap((int)vce.ActualWidth, (int)vce.ActualHeight, 96, 96, PixelFormats.Default);

                vce.Measure(vce.RenderSize);
                vce.Arrange(new Rect(vce.RenderSize));
                bmp.Render(vce);
                BitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));

                //创建图片存储路径,每个工程一个文件夹
                string directory = AppDomain.CurrentDomain.BaseDirectory + "Images" ;
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                //可能会多次拍摄,在图片后加上时间戳
                string imgName = "img" + DateTime.Now.ToString("yyyyMMddHHmmssffff");
                imgTempPath = AppDomain.CurrentDomain.BaseDirectory + "Images\\" + imgName + ".bmp";
                FileStream fstream = new FileStream(imgTempPath, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();
                vce.Pause();
                btnConfirm.Visibility = Visibility.Visible;
                btnReStart.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                if (vce.ActualWidth == 0 || vce.ActualHeight == 0)
                {
                    MessageBox.Show("请勿重复按钮");
                    return;
                }
                else
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }

        private void btnReStart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                vce.Play();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        
        //切换摄像头
        private void btnExChange_Click(object sender, RoutedEventArgs e)
        {
            if (MultimediaUtil.VideoInputNames.Length > 1)
            {
                if (vce.VideoCaptureSource == MultimediaUtil.VideoInputNames[0])
                {
                    vce.VideoCaptureSource = MultimediaUtil.VideoInputNames[1];
                }
                else
                {
                    vce.VideoCaptureSource = MultimediaUtil.VideoInputNames[0];
                }
            }
            else
            {
                MessageBox.Show("当前设备没有可切换的摄像头!");
            }
        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (imgTempPath != "" && File.Exists(imgTempPath))
                {
                    this.Close();
                }
                else
                {
                    MessageBox.Show("图片丢失,请重新拍摄。");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}

posted @ 2021-02-02 23:14  深秋无痕  阅读(3362)  评论(0编辑  收藏  举报