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 運行

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章