Photo

パソコンのカメラで撮影します。

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

プログラムの説明

  1. パソコンのカメラを使って写真を撮影します。
    Visual Studio を起動して[空白アプリ(ユニバーサル Windows)]を構築して下さい。
    プロジェクトの名前を Samples に合わせて CameraStarterKit とします。
  2. MainPage.xaml と MainPage.xaml.cs を下記のソースで置き換えます。
  3. ソリューションエクスプローラの参照を右クリックして [参照の追加][拡張] からDLLを追加します。

  4. Package.appxmanifest をダブルクリックして、設定画面を表示します。
    機能タグから「Web カメラ, ピクチャ ライブラリ, マイク」をチェックして下さい。

  5. コンパイル&実行するとカメラの使用許可が求められます。
    使用を許可するとパソコン画面にカメラで撮影中の画像が表示されます。
    写真アイコンをクリックすると、撮影された写真が PC\画像\SimplePhoto.jpg に保存されます。
  6. MainPage.xaml の後部に "PhotoButton" を追加して下さい。
    ボタンをクリックすると PhotoButton_Click() 関数が呼び出されます。
                <Button Name="PhotoButton" Click="PhotoButton_Click" IsEnabled="True">
                    <Viewbox MaxHeight="40" MaxWidth="40">
                        <SymbolIcon Symbol="Camera"/>
                    </Viewbox>
                </Button>
    
            </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;
    
    using Windows.Foundation;
    using Windows.Storage.Streams;
    using Windows.Storage.FileProperties;
    using Windows.Media.MediaProperties;
    using Windows.Graphics.Imaging;
    
    namespace CameraStarterKit
    {
        public sealed partial class MainPage : Page
        {
            // Prevent the screen from sleeping while the camera is running
            private readonly DisplayRequest _displayRequest = new DisplayRequest();
            private StorageFolder _captureFolder = null;
    
            // 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();
                    }
                }
            }
    
            // 写真アイコンをクリックすると PC\画像\SimplePhoto.jpg に保存されます。
            private async void PhotoButton_Click(object sender, RoutedEventArgs e)
            {
                await TakePhotoAsync();
            }
    
            private async Task TakePhotoAsync()
            {
                var stream = new InMemoryRandomAccessStream();
                Debug.WriteLine("Taking photo...");
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
    
                try
                {
                    var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
                    Debug.WriteLine("Photo taken! Saving to " + file.Path);
    
                    var photoOrientation = (PhotoOrientation)1;
                    await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
                    Debug.WriteLine("Photo saved!");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
                }
            }
     
            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);
                _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
            }
    
            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();
            }
    
            private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
            {
                using (var inputStream = stream)
                {
                    var decoder = await BitmapDecoder.CreateAsync(inputStream);
    
                    using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
                        var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
    
                        await encoder.BitmapProperties.SetPropertiesAsync(properties);
                        await encoder.FlushAsync();
                    }
                }
            }
    
        }
    }
    

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