Windows app 摄像头操作,拍照保存

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI;

using Windows.Media.Capture;
using Windows.Devices.Enumeration;
using System.Threading.Tasks;
using Windows.Media.MediaProperties;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Graphics.Imaging;


// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace AppDemoOpenCarema
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public static MainPage Current = null;
        private MediaCapture mediaCaptureMgr = null;

        public MainPage()
        {
            this.InitializeComponent();
            Current = this;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        private async void tsCameraSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            tsCameraSwitch.IsEnabled = false;
            if (tsCameraSwitch.IsOn)
            {
                bool isCameraFound = await CheckForRecordingDeviceAsync();
                if (isCameraFound)
                {
                    ShowMessage("正在打开摄像头...", false);
                    mediaCaptureMgr = new MediaCapture();
                    await mediaCaptureMgr.InitializeAsync();
                    cePreviewer.Source = mediaCaptureMgr;
                    await mediaCaptureMgr.StartPreviewAsync();
                    btnTakePhoto.IsEnabled = true;
                    btnSavePhoto.IsEnabled = true;
                    ShowMessage("摄像头已打开", false);
                }
                else
                {
                    ShowMessage("未找到摄像头", false);
                }
            }
            else
            {
                cePreviewer.Source = null;
                await mediaCaptureMgr.StopPreviewAsync();
                mediaCaptureMgr.Dispose();
                btnTakePhoto.IsEnabled = false;
                ShowMessage("摄像头已关闭", false);
            }
            tsCameraSwitch.IsEnabled = true;
        }

        private async void btnTakePhoto_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowMessage("正在拍摄", false);
                btnTakePhoto.IsEnabled = false;
                tsCameraSwitch.IsEnabled = false;
                btnSavePhoto.IsEnabled = false;
                string fileExtention = string.Empty;
                ImageEncodingProperties photoFormat = null;
                if (rbtnPhotoTypeBmp.IsChecked == true)
                {
                    photoFormat = ImageEncodingProperties.CreateBmp();
                    fileExtention = ".bmp";
                }
                else if (rbtnPhotoTypeJpg.IsChecked == true)
                {
                    photoFormat = ImageEncodingProperties.CreateJpeg();
                    fileExtention = ".Jpeg";
                }
                else if (rbtnPhotoTypePng.IsChecked == true)
                {
                    photoFormat = ImageEncodingProperties.CreatePng();
                    fileExtention = ".Png";
                }

                using (var imageStream = new InMemoryRandomAccessStream())
                {
                    await mediaCaptureMgr.CapturePhotoToStreamAsync(photoFormat, imageStream);
                    var writeableBmp = new WriteableBitmap(1, 1);
                    writeableBmp.SetSource(imageStream);
                    // and create it again because otherwise the WB isn't fully initialized and decoding
                    // results in a IndexOutOfRange
                    writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
                    imageStream.Seek(0);
                    writeableBmp.SetSource(imageStream);
                    imagePhoteViewer.Source = writeableBmp;
                }

                ShowMessage("已保存", false);
                btnTakePhoto.IsEnabled = true;
                tsCameraSwitch.IsEnabled = true;
                btnSavePhoto.IsEnabled = true;

            }
            catch (Exception ex)
            {
                ShowMessage("错误" + ex.Message, false);
                throw;
            }
        }

        private async void btnSavePhoto_Click(object sender, RoutedEventArgs e)
        {

            FileSavePicker picker = new FileSavePicker();
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeChoices.Add("Image", new List<string>() { ".jpg", ".jpeg", ".png", ".bmp" });
            picker.SuggestedFileName = "Picture" + DateTime.Now.ToString("yyyyMMddhhmmss");
            StorageFile file = await picker.PickSaveFileAsync();
            if (file != null)
            {
                var bitMap = imagePhoteViewer.Source as WriteableBitmap;
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                    if (file.FileType.ToLower().Contains("bmp"))
                    {
                        encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
                    }
                    else if (file.FileType.ToLower().Contains("png"))
                    {
                        encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
                    }

                    // Get pixels of the WriteableBitmap object 
                    Stream pixelStream = bitMap.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    // Save the image file 
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitMap.PixelWidth, (uint)bitMap.PixelHeight, 96.0, 96.0, pixels);
                    await encoder.FlushAsync();
                    ShowMessage("照片已保存至 " + file.Path, false);
                }

            }

        }

        /// <summary>
        /// show a message dialog
        /// </summary>
        /// <param name="msg">message to show</param>
        private void ShowMessage(string msg, bool isError)
        {
            //MessageDialog md = new MessageDialog(msg);
            //await md.ShowAsync();
            tbxStatus.Foreground = new SolidColorBrush(Colors.White);
            if (isError)
            {
                tbxStatus.Foreground = new SolidColorBrush(Colors.Red);
            }
            tbxStatus.Text = msg;
        }

        /// <summary>
        /// check is camera available
        /// </summary>
        /// <returns></returns>
        private static async Task<bool> CheckForRecordingDeviceAsync()
        {
            var cameraFound = false;
            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            if (devices.Count > 0)
            {
                cameraFound = true;
            }
            return cameraFound;
        }


    }
}
原文地址:https://www.cnblogs.com/fcq121/p/4892062.html