WPF: Доступ к Web-камере с помощью WinRT

В одной из прошлых заметок я использовал WinRT, чтобы в приложении WPF получить доступ к данным геолокации системы.
В этот раз я проверил доступ к веб-камере.

Фрагмент видео-демонстрации с конференции Microsoft:

  1. Как и раньше, изменим настройки проекта, указав минимальную версию ОС и .NET:
    ProjectPropertiesApplicationGeneral
    Target framework: .NET 6.0
    Target OS: Windows
    Target OS version: 10.0.17763.0
    Windows Presentation Foundation: Enable WPF for this project.

    TakeCameraPictureApp.csproj
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net6.0-windows10.0.17763.0</TargetFramework>
        <Nullable>enable</Nullable>
        <UseWPF>true</UseWPF>
      </PropertyGroup>
    
    </Project>
  2. Код дизайна окошка:
    MainWindow.xaml
    <Window x:Class="TakeCameraPictureApp.MainWindow"
            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:TakeCameraPictureApp"
            mc:Ignorable="d"
            Title="MainWindow" Height="500" Width="500">
        <StackPanel>
            <Border BorderBrush="#FFFB0F0F" BorderThickness="2">
                <Image x:Name="ImagePreview"
                       Width="400"
                       Height="400"
                       Stretch="Uniform"/>
            </Border>
            <Button Content="Take Picture"
                    Width="100"
                    Height="40"
                    Margin="0,10,0,0"
                    Click="TakePicture_Click"/>
        </StackPanel>
    </Window>
    Тут я сделал рамку, чтобы было видно, где изображение с камеры, а где границы области.

     

  3. Логика кнопки с кодом для скриншота изображения камеры:
    MainWindow.xaml.cs
    using System;
    using System.Windows;
    using System.Windows.Media.Imaging;
    using Windows.Media.Capture;
    using Windows.Media.MediaProperties;
    using Windows.Storage;
    
    namespace TakeCameraPictureApp
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            MediaCapture captureManager;
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private async void TakePicture_Click(object sender, RoutedEventArgs e)
            {
                // Initialize Camera
                captureManager = new MediaCapture();
                await captureManager.InitializeAsync();
    
                // Set the format
                ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
    
                // Create storage file in local app storage
                StorageFile file = await KnownFolders.CameraRoll.CreateFileAsync("TestPhoto.jpg", CreationCollisionOption.GenerateUniqueName);
    
                // Take a photo
                await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);
    
                // Get photo as a BitmapImage
                BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));
    
                // imagePreview - is an <Image> object defined in XAML
                ImagePreview.Source = bmpImage;
            }
    
        }
    }
  4. Результат после нажатия кнопки:
    WPF: Доступ к Web-камере с помощью WinRT

    Изображение с камеры будет сохранено в папку пользователя Pictures\Camera Roll.

     

У меня на компе веб-камера Defender G-lens 2577, так вот с её драйверами в Visual Studio выкидывает исключение:

System.Runtime.InteropServices.COMException: ‘Capture device that is present on the system is not supported by Media Foundation.’

Так что пришлось скриншот делать с ноутбука.

 



Подписаться
Уведомление о
guest
0 Комментарий
Inline Feedbacks
View all comments