WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

WPF摄像头使用(WPFMediaKit)

Posted on   WebEnh  阅读(820)  评论(0编辑  收藏  举报

添加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);
            }
        }

    }
}

 
 
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2020-07-10 跨域问题服务端解决办法 Request header field Authorization is not allowed by Access-Control-Allow-Headers
2018-07-10 .net OADate 转javascript的Datetime js 5位 日期 转换
2017-07-10 (转载)开发人员必须用到的开发软件破解
2017-07-10 HTML5漫谈(7)——如何保护HTML5应用代码
2017-07-10 【转】使用Jasob混淆javascript代码
2016-07-10 SQL 查询数据库中所有表信息
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多