与众不同 windows phone (42) - 8.0 相机和照片: 通过 PhotoCaptureDevice 捕获照片

[源码下载]


与众不同 windows phone (42) - 8.0 相机和照片: 通过 PhotoCaptureDevice 捕获照片



作者:webabcd


介绍
与众不同 windows phone 8.0 之 相机和照片

  • 通过 PhotoCaptureDevice 捕获照片



示例
演示 PhotoCaptureDevice(wp8)的应用
CameraAndPhoto/PhotoCaptureDeviceDemo.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.CameraAndPhoto.PhotoCaptureDeviceDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel>
            
            <StackPanel Orientation="Horizontal">
                <Canvas Width="240" Height="180" RenderTransformOrigin="0.5 0.5">
                    <Canvas.Background>
                        <VideoBrush x:Name="videoBrush" />
                    </Canvas.Background>
                    <Canvas.RenderTransform>
                        <RotateTransform x:Name="rt" />
                    </Canvas.RenderTransform>
                </Canvas>
                <Image Name="imgPreview" Width="240" Height="180" />
            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="0 50 0 0">
                <Button Name="btnCapture" Content="照相"  Click="btnCapture_Click" />
                <Button Name="btnFocus" Content="自动对焦" Click="btnFocus_Click" />
            </StackPanel>

            <TextBlock x:Name="lblMsg" TextWrapping="Wrap" Margin="0 10 0 0" />
            
        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>


CameraAndPhoto/PhotoCaptureDeviceDemo.xaml.cs

/*
 * 演示 PhotoCaptureDevice(wp8)的应用
 * 
 * 关于 PhotoCamera(wp7)的应用参见
 * http://www.cnblogs.com/webabcd/archive/2012/08/13/2635698.html
 * http://www.cnblogs.com/webabcd/archive/2012/08/15/2639428.html
 * 
 * 
 * 注:
 * 需要在 manifest 中增加配置 <Capability Name="ID_CAP_ISV_CAMERA" /> <Capability Name="ID_CAP_MEDIALIB_PHOTO" />
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Windows.Phone.Media.Capture;
using Microsoft.Devices;
using System.IO;
using Microsoft.Xna.Framework.Media;
using Microsoft.Phone;

namespace Demo.CameraAndPhoto
{
    public partial class PhotoCaptureDeviceDemo : PhoneApplicationPage
    {
        private PhotoCaptureDevice _captureDevice;

        public PhotoCaptureDeviceDemo()
        {
            InitializeComponent();

            this.Loaded += PhotoCaptureDeviceDemo_Loaded;
        }

        private async void PhotoCaptureDeviceDemo_Loaded(object sender, RoutedEventArgs e)
        {
            // 一些概述类的说明
            Summary();

            // 是否有后置摄像头
            if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back))
            {
                // 获取后置摄像头照相时的可用分辨率
                IReadOnlyList<Windows.Foundation.Size> supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                Windows.Foundation.Size resolution = supportedResolutions[0];

                try
                {
                    // 让后置摄像头以指定的分辨率捕获镜头内容
                    _captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution);


                    /*
                     * SetCaptureResolutionAsync() - 设置捕获照片的分辨率
                     * SetPreviewResolutionAsync() - 设置捕获照片的预览图的分辨率
                     * CaptureResolution - 获取当前捕获的分辨率
                     * PreviewResolution - 获取当前捕获的预览图的分辨率
                     * FocusRegion - 对焦区域
                     * SensorLocation - 当前摄像头的位置(CameraSensorLocation 枚举:Back 或 Front)
                     * SensorRotationInDegrees - 获取照相机传感器相对于屏幕的旋转度数
                     */


                    /*
                     * KnownCameraPhotoProperties 属性集包括
                     *     FlashMode - 闪光灯模式:FlashState.On, FlashState.Auto, FlashState.Off
                     *     FlashPower - 闪光亮度,无单位且不同设备上的值不同
                     *     FocusIlluminationMode - 闪光灯的对焦方式:FocusIlluminationMode.Auto, FocusIlluminationMode.Off, FocusIlluminationMode.On
                     *     ExposureCompensation - 曝光补偿,单位:1/6 EV
                     *     ExposureTime - 曝光时间,单位:微秒
                     *     ManualWhiteBalance - 手动设置白平衡
                     *     WhiteBalancePreset - 设置预置白平衡(WhiteBalancePreset 枚举,包括多云、荧光灯等等)
                     *     LockedAutoFocusParameters - 自动对焦、自动曝光或自动白平衡参数(AutoFocusParameters 枚举,有 flag 标记)
                     *         AutoFocusParameters.None - 对焦、曝光和白平衡全自动
                     *         AutoFocusParameters.Focus - 暂停自动对焦
                     *         AutoFocusParameters.Exposure - 暂停自动曝光
                     *         AutoFocusParameters.WhiteBalance - 暂停自动白平衡
                     *     Iso - 感光度
                     *     SceneMode - 场景模式(CameraSceneMode 枚举,包括人像优化、夜景优化等等)
                     */
                    _captureDevice.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.On);


                    /*
                     * KnownCameraGeneralProperties 属性集包括
                     *     AutoFocusRange - 自动对焦的范围(AutoFocusRange 枚举,包括微距等)
                     *     EncodeWithOrientation - 照片捕获完成后编码时的旋转角度,必须是 90 的倍数
                     *     SpecifiedCaptureOrientation -  照片捕获完成后照片元数据中的旋转角度,必须是 90 的倍数
                     *     IsShutterSoundEnabledByUser - 用户是否启用了快门声音,只读
                     *     IsShutterSoundRequiredForRegion - 运行应用程序的区域是否需要快门声音(有些区域为了保护隐私,要求照相或录像必须要有快门声音),只读
                     *     PlayShutterSoundOnCapture - 指定捕获时是否播放快门声音
                     *     ManualFocusPosition - 手动对焦的位置
                     */
                    _captureDevice.SetProperty(KnownCameraGeneralProperties.AutoFocusRange, AutoFocusRange.Normal);
                    _captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, _captureDevice.SensorRotationInDegrees);


                    // 获取指定属性的值
                    // _captureDevice.GetProperty(KnownCameraGeneralProperties.IsShutterSoundEnabledByUser);

                    /*
                     * 获取指定的范围类属性在当前相机中所允许的值的范围
                     */
                    // PhotoCaptureDevice.GetSupportedPropertyRange(CameraSensorLocation.Back, KnownCameraPhotoProperties.ExposureCompensation);

                    /*
                     * 获取指定的值类属性在当前相机中所允许的值的列表
                     */
                    // PhotoCaptureDevice.GetSupportedPropertyValues(CameraSensorLocation.Back, KnownCameraPhotoProperties.FlashMode);

                    // 实时显示捕获的内容
                    videoBrush.SetSource(_captureDevice); // 扩展方法来自:Microsoft.Devices.CameraVideoBrushExtensions

                    rt.Angle = _captureDevice.SensorRotationInDegrees;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("没有后置摄像头");
            }
        }

        // 照相
        private async void btnCapture_Click(object sender, RoutedEventArgs e)
        {
            // 创建捕获序列,目前系统仅支持单帧捕获
            CameraCaptureSequence seq = _captureDevice.CreateCaptureSequence(1);

            // 设置序列中的指定帧的 KnownCameraPhotoProperties 属性和 KnownCameraGeneralProperties 属性
            // seq.Frames[0].DesiredProperties[KnownCameraPhotoProperties.FlashMode] = FlashState.On;
            // seq.Frames[0].DesiredProperties[KnownCameraGeneralProperties.AutoFocusRange] = AutoFocusRange.Infinity;

            // 捕获到的图片的内存流
            MemoryStream captureStream = new MemoryStream();
            // 捕获到的图片的预览图的内存流
            MemoryStream captureStreamPreview = new MemoryStream();

            // 设置捕获到的图片的内存流
            seq.Frames[0].CaptureStream = captureStream.AsOutputStream();
            // 设置捕获到的图片的预览图的内存流
            seq.Frames[0].ThumbnailStream = captureStreamPreview.AsOutputStream();

            try
            {
                // 根据捕获序列的设置,准备好捕获前的相关数据
                await _captureDevice.PrepareCaptureSequenceAsync(seq);

                // 开始捕获
                await seq.StartCaptureAsync();

                captureStream.Position = 0;
                captureStreamPreview.Position = 0;

                // 保存捕获到的图片到“本机照片”
                MediaLibrary library = new MediaLibrary();
                Picture picture = library.SavePictureToCameraRoll("xxx.jpg", captureStream); // 如果有重名,会自动重命名

                // 显示捕获到的图片的预览图(也可以通过 picture.GetThumbnail() 来获取预览图)
                imgPreview.Source = PictureDecoder.DecodeJpeg(captureStreamPreview);

                lblMsg.Text += "拍照完成,且已保存到照片中心";
                lblMsg.Text += System.Environment.NewLine;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            captureStream.SetLength(0);
            captureStreamPreview.SetLength(0);

            captureStream.Dispose();
            captureStreamPreview.Dispose();
        }

        // 自动对焦
        private async void btnFocus_Click(object sender, RoutedEventArgs e)
        {
            // 启动自动对焦、自动曝光和自动白平衡,参考 LockedAutoFocusParameters
            CameraFocusStatus status = await _captureDevice.FocusAsync();
            lblMsg.Text += status.ToString();
            lblMsg.Text += System.Environment.NewLine;

            // 复位对焦
            // _captureDevice.ResetFocusAsync();
        }


        private void Summary()
        {
            lblMsg.Text = "";

            // 获取电话上的可用相机
            foreach (CameraSensorLocation csl in PhotoCaptureDevice.AvailableSensorLocations)
            {
                // Back 或 Front
                lblMsg.Text += "摄像头:" + csl.ToString();
                lblMsg.Text += System.Environment.NewLine;


                // 捕获所支持的分辨率
                lblMsg.Text += "捕获照片的可用分辨率:";
                foreach (var size in PhotoCaptureDevice.GetAvailableCaptureResolutions(csl))
                {
                    lblMsg.Text += size.Width + "*" + size.Height + " ";
                }
                lblMsg.Text += System.Environment.NewLine;


                // 捕获后的预览图所支持的分辨率
                lblMsg.Text += "捕获照片的预览图的可用分辨率:";
                foreach (var size in PhotoCaptureDevice.GetAvailablePreviewResolutions(csl))
                {
                    lblMsg.Text += size.Width + "*" + size.Height + " ";
                }
                lblMsg.Text += System.Environment.NewLine;


                lblMsg.Text += "是否支持自动对焦:" + PhotoCaptureDevice.IsFocusSupported(csl);
                lblMsg.Text += System.Environment.NewLine;
                lblMsg.Text += "是否支持以编程方式自动对焦:" + PhotoCaptureDevice.IsFocusRegionSupported(csl);
                lblMsg.Text += System.Environment.NewLine;
                lblMsg.Text += System.Environment.NewLine;


                // 关于 CameraButtons 参见以前的文章:http://www.cnblogs.com/webabcd/archive/2012/08/15/2639428.html
                // CameraButtons.ShutterKeyHalfPressed 事件,CameraButtons.ShutterKeyPressed 事件,CameraButtons.ShutterKeyReleased 事件
            }
        }
    }
}



OK
[源码下载]

posted @ 2013-12-23 08:28  webabcd  阅读(2558)  评论(2编辑  收藏  举报