WPF 加载摄像机视频

WPF 加载摄像机视频

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

视频显示

1.引入AForge库文件

NUGet导入

AForge

AForge.Vedio

AForge.Vedio.DirectShow

2.设置UI

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


    
        
            
            
        

        
            
        

        
            
                
            
        

    


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
{
    /// 
    /// CameraWindow.xaml 的交互逻辑
    /// 
    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)
            {
            }
        }

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

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


        public List 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();

                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();
        }

        /// 
        /// 将Bitmap格式的数据转换成ImageSource
        /// 获取 ImageSource 格式的图片
        /// 
        /// 
        /// 
        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);
            //}
        }

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


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

                myCaptureDevice = null;
            }

        }

        /// 
        /// 摄像机
        /// 
        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 运行

WPF 加载摄像机视频_第1张图片

你可能感兴趣的:(C#,WPF)