WPF 加载摄像机视频

WPF 加载摄像机视频

WPF 显示摄像机可以借助AForge进行实现视频显示和数据录制。

视频显示

1.引入AForge库文件

NUGet导入

AForge

AForge.Vedio

AForge.Vedio.DirectShow

2.设置UI

添加一个Image控件,用于视频呈现。

<Window x:Class="Rxbit.Views.Scane.CameraWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Rxbit.Views.Scane"
        mc:Ignorable="d"
        Title="CameraWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel>
            <ComboBox Name="SS" DisplayMemberPath="UUYY" SelectedValuePath="Index" SelectionChanged="SS_SelectionChanged"/>
        </StackPanel>

        <Grid Grid.Row="1" >
            <Border BorderBrush="SaddleBrown" BorderThickness="2">
                <Image x:Name="ImgCamera" />
            </Border>
        </Grid>

    </Grid>
</Window>

3.通过Aforge获取视频并显示到界面

using AForge.Video;
using AForge.Video.DirectShow;
using Rxbit.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Rxbit.Views.Scane
{
    /// <summary>
    /// CameraWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CameraWindow : Window
    {
        private FilterInfoCollection videoDevices;

        public CameraWindow()
        {
            InitializeComponent();
            Loaded += CameraWindow_Loaded;
            Closed += CameraWindow_Closed;
        }

        private void CameraWindow_Closed(object sender, EventArgs e)
        {
            try
            {
                CloseCaptureDevice();
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// ComboBox显示类型
        /// </summary>
        public class CaItem
        {
            /// <summary>
            /// 在videoDevices中的索引,从0开始
            /// </summary>
            public int Index { get; set; }

            /// <summary>
            /// 显示的文本
            /// </summary>
            public string UUYY { get; set; }
        }


        public List<CaItem> CaItems { get; set; }

        private void CameraWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                CaItems = new List<CaItem>();

                for (int i = 0; i < videoDevices.Count; i++)
                {
                    CaItems.Add(new CaItem() { Index = i, UUYY = videoDevices[i].Name });

                }
                SS.ItemsSource = CaItems;

                SS.SelectedIndex = 0;

            }
            catch (ApplicationException)
            {
                SS.Items.Add("No local capture devices");
                videoDevices = null;
            }
        }

        private void myCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();

            //currentBitmap = bitmap.Clone(
            // new RectangleF((bitmap.Size.Width - 640) / 2, (bitmap.Size.Height - 480) / 2, 640, 480), //显示图像的宽度为295像素,高度为413像素
            //System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            bitmap = bitmap.Clone(
               new RectangleF((bitmap.Size.Width - 640) / 2, (bitmap.Size.Height - 480) / 2, 640, 480), //显示图像的宽度为295像素,高度为413像素
               System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            Thread.Sleep(10);

            //mutex.WaitOne();
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                ImgCamera.Source = ImageSourceForBitmap(bitmap);
            }), DispatcherPriority.Background, null);

            // mutex.ReleaseMutex();
        }

        /// <summary>
        /// 将Bitmap格式的数据转换成ImageSource
        /// 获取 ImageSource 格式的图片
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public ImageSource ImageSourceForBitmap(Bitmap bmp)
        {
            var handle = bmp.GetHbitmap();
            try
            {
                ImageSource newsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                DeleteObject(handle);
                return newsource;
            }
            catch (Exception)
            {
                DeleteObject(handle);
                return null;
            }
            //finally
            //{
            //    DeleteObject(handle);
            //}
        }

        /// <summary>
        /// 删除非托管对象对象
        /// </summary>
        /// <param name="hObject"></param>
        /// <returns></returns>
        [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DeleteObject([In] IntPtr hObject);


        /// <summary>
        /// 关闭设备
        /// </summary>
        public void CloseCaptureDevice()
        {
            if (myCaptureDevice != null)
            {
                if (myCaptureDevice.IsRunning)
                {
                    myCaptureDevice.SignalToStop();
                }

                myCaptureDevice = null;
            }

        }

        /// <summary>
        /// 摄像机
        /// </summary>
        VideoCaptureDevice myCaptureDevice;
        bool sst = true;
        private void SS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int a = Convert.ToInt32((sender as ComboBox).SelectedValue.ToString());

            CloseCaptureDevice();

            myCaptureDevice = new VideoCaptureDevice(videoDevices[a].MonikerString);//myCaptureDevice的类型为VideoCaptureDevice,
            myCaptureDevice.NewFrame += new NewFrameEventHandler(myCaptureDevice_NewFrame);
            myCaptureDevice.DesiredFrameSize = new System.Drawing.Size(640, 480);//436, 360
            myCaptureDevice.DesiredFrameRate = 60;
            myCaptureDevice.Start();
        }

    }
}

4. F5 运行

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值