Camera

パソコンのカメラを使います。

前田稔の超初心者のプログラム入門

プログラムの説明

  1. 元ネタは Microsoft のサンプルプログラム Windows-universal-Samples-Master です。
    Visual Studio を起動して[空白アプリ(ユニバーサル Windows)]を構築して下さい。
    プロジェクトの名前を Samples に合わせて CameraStarterKit とします。
  2. MainPage.xaml と MainPage.xaml.cs を下記のソースで置き換えます。
  3. ソリューションエクスプローラの参照を右クリックして [参照の追加][拡張] からDLLを追加します。

    これでコンパイルするとエラーは無くなりますが、実行するとコケます。
  4. Package.appxmanifest をダブルクリックして、設定画面を表示します。
    機能タグから「Web カメラ, ピクチャ ライブラリ, マイク」をチェックして下さい。

  5. コンパイル&実行するとカメラの使用許可が求められます。
    使用を許可するとパソコン画面にカメラで撮影中の画像が表示されます。
    写真の撮影は Photo を参照して下さい。
    動画の撮影は Video を参照して下さい。
  6. MainPage.xaml のソースコードです。
    <Page
        x:Class="CameraStarterKit.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:CameraStarterKit"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <Page.Resources>
            <SolidColorBrush x:Key="TranslucentBlackBrush" Color="Black" Opacity="0.3"/>
        </Page.Resources>
        
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
            <!--Camera preview-->
            <CaptureElement Name="PreviewControl" Stretch="Uniform"/>
         
            <!-- Capture + Record buttons -->       
            <StackPanel HorizontalAlignment="Right" VerticalAlignment="Center">
                <StackPanel.Resources>
                    <Style TargetType="Button">
                        <Setter Property="Margin" Value="10,40"/>
                        <Setter Property="MinWidth" Value="80"/>
                        <Setter Property="MinHeight" Value="80"/>
                        <Setter Property="Foreground" Value="White"/>
                        <Setter Property="Background" Value="{StaticResource TranslucentBlackBrush}"/>
                        <Setter Property="BorderBrush" Value="White"/>
                        <Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
                    </Style>
                </StackPanel.Resources>
            </StackPanel>
        </Grid>
    </Page>
    
  7. MainPage.xaml.cs のソースコードです。
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.ApplicationModel;
    using Windows.Devices.Enumeration;
    using Windows.Foundation.Metadata;
    using Windows.Graphics.Display;
    using Windows.Media;
    using Windows.Media.Capture;
    using Windows.Storage;
    using Windows.System.Display;
    using Windows.UI.Core;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    
    namespace CameraStarterKit
    {
        public sealed partial class MainPage : Page
        {
            // Prevent the screen from sleeping while the camera is running
            private readonly DisplayRequest _displayRequest = new DisplayRequest();
    
            // MediaCapture and its state variables
            private MediaCapture _mediaCapture;
            private bool _isInitialized;
    
            // UI state
            private bool _isActivePage;
            private bool _isUIActive;
            private Task _setupTask = Task.CompletedTask;
    
            // Information about the camera device
            private bool _mirroringPreview;
    
            public MainPage()
            {
                this.InitializeComponent();
    
                // Do not cache the state of the UI when suspending/navigating
                NavigationCacheMode = NavigationCacheMode.Disabled;
            }
    
            private void Application_Suspending(object sender, SuspendingEventArgs e)
            {
                var deferral = e.SuspendingOperation.GetDeferral();
                var task = Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                {
                    await SetUpBasedOnStateAsync();
                    deferral.Complete();
                });
            }
    
            protected override async void OnNavigatedTo(NavigationEventArgs e)
            {
                // Useful to know when to initialize/clean up the camera
                Application.Current.Suspending += Application_Suspending;
                Window.Current.VisibilityChanged += Window_VisibilityChanged;
    
                _isActivePage = true;
                await SetUpBasedOnStateAsync();
            }
    
            private async void Window_VisibilityChanged(object sender, VisibilityChangedEventArgs args)
            {
                await SetUpBasedOnStateAsync();
            }
    
            private async Task InitializeCameraAsync()
            {
                if (_mediaCapture == null)
                {
                    // Attempt to get the back camera if one is available, but use any camera device if not
                    var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
    
                    if (cameraDevice == null)
                    {
                        Debug.WriteLine("No camera device found!");
                        return;
                    }
    
                    // Create MediaCapture and its settings
                    _mediaCapture = new MediaCapture();
    
                    var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
    
                    // Initialize MediaCapture
                    try
                    {
                        await _mediaCapture.InitializeAsync(settings);
                        _isInitialized = true;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Debug.WriteLine("The app was denied access to the camera");
                    }
    
                    // If initialization succeeded, start the preview
                    if (_isInitialized)
                    {
                        await StartPreviewAsync();
                    }
                }
            }
    
            private async Task StartPreviewAsync()
            {
                Debug.WriteLine("StartPreviewAsync");
                // Prevent the device from sleeping while the preview is running
                _displayRequest.RequestActive();
    
                // Set the preview source in the UI and mirror it if necessary
                PreviewControl.Source = _mediaCapture;
                PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
    
                // Start the preview
                await _mediaCapture.StartPreviewAsync();
            }
    
            private async Task SetUpBasedOnStateAsync()
            {
                Debug.WriteLine("SetUpBasedOnStateAsync");
                // Avoid reentrancy: Wait until nobody else is in this function.
                while (!_setupTask.IsCompleted)
                {
                    await _setupTask;
                }
    
                bool wantUIActive = _isActivePage && Window.Current.Visible;
    
                if (_isUIActive != wantUIActive)
                {
                    _isUIActive = wantUIActive;
    
                    Func<Task> setupAsync = async () =>
                    {
                        if (wantUIActive)
                        {
                            await SetupUiAsync();
                            await InitializeCameraAsync();
                        }
                        else
                        {
                            await CleanupUiAsync();
                        }
                    };
                    _setupTask = setupAsync();
                }
    
                await _setupTask;
            }
    
            private async Task SetupUiAsync()
            {
                // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
    
                // Hide the status bar
                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
                {
                    await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
                }
    
                //RegisterEventHandlers();
                var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
            }
    
            private async Task CleanupUiAsync()
            {
                // Show the status bar
                if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
                {
                    await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
                }
    
                // Revert orientation preferences
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
            }
    
            private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
            {
                // Get available devices for capturing pictures
                var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
    
                // Get the desired camera by panel
                DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
    
                // If there is no device mounted on the desired panel, return the first device found
                return desiredDevice ?? allVideoDevices.FirstOrDefault();
            }
        }
    }
    

超初心者のプログラム入門(C# Frame Work)