相机功能是手机区别于PC的一大功能,在做手机应用时,如果合理的利用了拍照功能,可能会给自己的应用增色很多。使用Windows Phone的相机功能,有两种方法,一种是使用PhotoCamera类来构建自己的相机UI,另外一种是通过CameraCaptureTask选择器来实现该功能。

他们的区别是:

  • PhotoCamera类允许应用控制照片属性,如 ISO、曝光补偿和手动对焦位置,应用可以对照片有更多的控制,当然也会麻烦很多。需要实现闪光灯、对焦、分辨率、快门按钮等操作。
  • CameraCaptureTask拍照会调用系统的相机功能,返回一个有照片数据的返回值,同时一旦拍照,就会进入手机相册。

一. CameraCaptureTask选择器。

  1. 首先需要引用
using Microsoft.Phone.Tasks;
  1. 声明任务对象,需要在页面的构造函数之前声明
CameraCaptureTask cameraCaptureTask;

在构造函数中实例化CameraCaptureTask对象,并且注册回调方法。

cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);

在应用程序中的所需位置添加以下代码,例如按键点击事件中

cameraCaptureTask.Show();

在页面中添加已完成事件处理程序的代码。此代码在用户完成任务后运行。结果是一个 PhotoResult对象,该对象公开包含图像数据的流。

void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString()); //Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//myImage.Source = bmp;
}
}

这部分比较简单,就不多讲了,给个demo吧:http://pan.baidu.com/s/1pJ0Polt

二. PhotoCamera

  PhotoCamera是在windows phone os 7.1开始加入的,在使用之前需要给应用添加访问相机的权限,在

WMAppManifest.xml中添加ID_CAP_ISV_CAMERA

  1. 创建UI

在创建取景器时,一般会使用VideoBrush,如果需要支持横竖屏的切换,则需要加入RelativeTransform,如下代码是一个典型的相机UI

<!-- 相机取景器 -->

        <Canvas x:Name="VideoCanvas">

            <Canvas.Background>

                <VideoBrush x:Name="BackgroundVideoBrush" >

                    <VideoBrush.RelativeTransform>

                        <CompositeTransform x:Name="VideoBrushTransform" CenterY="0.5" CenterX="0.5"/>

                    </VideoBrush.RelativeTransform>

                </VideoBrush>

            </Canvas.Background>

        </Canvas>

当然你还要考虑页面上的其他元素,比如点击取景器对焦,快门、闪光灯按钮等,这些可随个人洗好自定义。

  1. 实现取景器和相关相机事件。
    1. 首先实现取景器,先判断手机有没有相关的硬件设备(背部相机(主)或者前部相机)
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||

                 (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))

            {

                // Initialize the camera, when available.

                if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing))

                {

                    // Use front-facing camera if available.

                    cam = new Microsoft.Devices.PhotoCamera(CameraType.FrontFacing);

                }

                else

                {

                    // Otherwise, use standard camera on back of device.

                    cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);

                }

    //Set the VideoBrush source to the camera.

                viewfinderBrush.SetSource(cam);

            }

            else

            {

                // The camera is not supported on the device.

                this.Dispatcher.BeginInvoke(delegate()

                {

                    // Write message.

                    txtDebug.Text = "A Camera is not available on this device.";

                });

                // Disable UI.

                ShutterButton.IsEnabled = false;

                FlashButton.IsEnabled = false;

                AFButton.IsEnabled = false;

                ResButton.IsEnabled = false;

            }
  1. 在加载时也需要实现各种操作事件
// Event is fired when the PhotoCamera object has been initialized.

                cam.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);

                // Event is fired when the capture sequence is complete.

                cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_CaptureCompleted);

                // Event is fired when the capture sequence is complete and an image is available.

                cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);

                // Event is fired when the capture sequence is complete and a thumbnail image is available.

                cam.CaptureThumbnailAvailable += new EventHandler<ContentReadyEventArgs>(cam_CaptureThumbnailAvailable);

                // The event is fired when auto-focus is complete.

                cam.AutoFocusCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_AutoFocusCompleted);

                // The event is fired when the viewfinder is tapped (for focus).

                viewfinderCanvas.Tap += new EventHandler<GestureEventArgs>(focus_Tapped);

                // The event is fired when the shutter button receives a half press.

                CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;

                // The event is fired when the shutter button receives a full press.

                CameraButtons.ShutterKeyPressed += OnButtonFullPress;

                // The event is fired when the shutter button is released.

                CameraButtons.ShutterKeyReleased += OnButtonRelease;
  1. 上面加载了这么多事件,需要在离开此页面时释放:
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)

        {

            if (cam != null)

            {

                // Dispose camera to minimize power consumption and to expedite shutdown.

                cam.Dispose();

                // Release memory, ensure garbage collection.

                cam.Initialized -= cam_Initialized;

                cam.CaptureCompleted -= cam_CaptureCompleted;

                cam.CaptureImageAvailable -= cam_CaptureImageAvailable;

                cam.CaptureThumbnailAvailable -= cam_CaptureThumbnailAvailable;

                cam.AutoFocusCompleted -= cam_AutoFocusCompleted;

                CameraButtons.ShutterKeyHalfPressed -= OnButtonHalfPress;

                CameraButtons.ShutterKeyPressed -= OnButtonFullPress;

                CameraButtons.ShutterKeyReleased -= OnButtonRelease;

            }

        }

上面这些事件,看看名字估计也就懂了是干啥的了,这里说明下他们的执行顺序,CaptureThumbnailAvailable —>CaptureImageAvailable —>CaptureCompleted。

  1. 拍出了照片后需要保存,可以保存到相机中,使用的是SavePictureToCameraRoll方法,同时可以保存到独立存储空间中,方便以后读取(如果仅仅保存在相册中,下次读取时必须使用照片选择器让用户去选择照片):
public void cam_CaptureThumbnailAvailable(object sender, ContentReadyEventArgs e)

        {

            string fileName = savedCounter + "_th.jpg";

            try

            {

                // Write message to UI thread.

                Deployment.Current.Dispatcher.BeginInvoke(delegate()

                {

                    txtDebug.Text = "Captured image available, saving thumbnail.";

                });

                // Save thumbnail as JPEG to isolated storage.

                using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())

                {

                    using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))

                    {

                        // Initialize the buffer for 4KB disk pages.

                        byte[] readBuffer = new byte[];

                        int bytesRead = -;

                        // Copy the thumbnail to isolated storage.

                        while ((bytesRead = e.ImageStream.Read(readBuffer, , readBuffer.Length)) > )

                        {

                            targetStream.Write(readBuffer, , bytesRead);

                        }

                    }

                }

                // Write message to UI thread.

                Deployment.Current.Dispatcher.BeginInvoke(delegate()

                {

                    txtDebug.Text = "Thumbnail has been saved to isolated storage.";

                });

            }

            finally

            {

                // Close image stream

                e.ImageStream.Close();

            }

        }

保存照片有两个方法:SavePicture和SavePictureToCameraRoll,前面的方法是保存到照片中心“保存的照片”中,后一种方法是保存到“本机拍照”中。

  1. 对于闪光灯、对焦、分辨率以及快门都有相应的方法,从上面的代码中也可以看到快门有半按、全按、释放等事件,这里不再赘述,可以从源代码中看到相关的事件。

这个例子的demo是微软提供的,比较详细,源码如下:http://pan.baidu.com/s/1c0rIqSK

参考文章:Windows Phone 的相机和照片

Windows Phone 开发——相机功能开发的更多相关文章

  1. 微信小程序开发-蓝牙功能开发

    0. 前言 这两天刚好了解了一下微信小程序的蓝牙功能.主要用于配网功能.发现微信的小程序蓝牙API已经封装的很好了.编程起来很方便.什么蓝牙知识都不懂的情况下,不到两天就晚上数据的收发了,剩下的就是数 ...

  2. FastAPI(七十)实战开发《在线课程学习系统》接口开发--留言功能开发

    在之前的文章:FastAPI(六十九)实战开发<在线课程学习系统>接口开发--修改密码,这次分享留言功能开发 我们能梳理下对应的逻辑 1.校验用户是否登录 2.校验留言的用户是否存在 3. ...

  3. Kinect开发笔记之二Kinect for Windows 2.0新功能

    这是本博客翻译文档的第一篇文章.笔者已经苦逼的竭尽全力的在翻译了.但无奈英语水平也是非常有限.不正确或者不妥当不准确的地方必定会有,还恳请大家留言或者邮件我以批评指正.我会虚心接受. 谢谢大家.   ...

  4. Windows 8.1 低功耗蓝牙开发

    1. 概述 在蓝牙4.0发布以前,给大家的直观印象就是蓝牙耳机,它就是用来满足短距离内中等带宽的音频通信需求.然而蓝牙4.0发布之后,用途就大不一样了,特别是现在物联网和可穿戴之风盛行的年代,很多小玩 ...

  5. ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器

    ASP.NET MVC 中应用Windows服务以及Webservice服务开发分布式定时器一:闲谈一下:1.现在任务跟踪管理系统已经开发快要结束了,抽一点时间来写一下,想一想自己就有成就感啊!!  ...

  6. 《深入浅出Windows Phone 8.1 应用开发》基于Runtime框架全新升级版

    <深入浅出Windows Phone 8.1 应用开发>使用WP8.1 Runtime框架最新的API重写了上一本<深入浅出Windows Phone 8应用开发>大部分的的内 ...

  7. 8个必备的PHP功能开发

    这篇文章主要介绍了8个必备的PHP功能开发,需要的朋友可以参考下 PHP开发的程序员应该清楚,PHP中有很多内置的功能,掌握了它们,可以帮助你在做PHP开发时更加得心应手,本文将分享8个开发必备的PH ...

  8. C# Windows Phone 8 WP8 高级开发,制作不循环 Pivot ,图片(Gallery)导览不求人! 内附图文教学!!

    原文:C# Windows Phone 8 WP8 高级开发,制作不循环 Pivot ,图片(Gallery)导览不求人! 内附图文教学!! 一般我们在开发Winodws Phone APP 的时候往 ...

  9. Windows 8.1 store app 开发笔记

    原文:Windows 8.1 store app 开发笔记 零.简介 一切都要从博彦之星比赛说起.今年比赛的主题是使用Bing API(主要提到的有Bing Map API.Bing Translat ...

随机推荐

  1. 读书笔记——Windows核心编程(8)Interlocked系列函数

    先让我们来复习下小学知识 A+B=C//式中A为被加数,B为加数. A-B=C//式中A为被减数,B为减数. 再让我们来明确一个知识点:返回值为void的Windows函数意味着一定会执行成功. -- ...

  2. Climbing Stairs

    Climbing Stairs https://leetcode.com/problems/climbing-stairs/ You are climbing a stair case. It tak ...

  3. Sample: Write And Read data from HDFS with java API

    HDFS: hadoop distributed file system 它抽象了整个集群的存储资源,可以存放大文件. 文件采用分块存储复制的设计.块的默认大小是64M. 流式数据访问,一次写入(现支 ...

  4. 通用cube refresh方案

    通用cube refresh c# script 解决方法: 需要设置的变量如下: User::varcubename,User::varolapconnstr,User::varolapdbname ...

  5. javaScript事件(三)事件对象

    一.事件 二.事件流 以上内容见:javaScript事件(一)事件流 三.事件处理程序 四.IE事件处理程序 以上内容见javaScript事件(二)事件处理程序 五.事件对象 1.认识事件对象 事 ...

  6. 【Ext.Net学习笔记】07:后续

    这些笔记都是在这个地址看到的:http://www.qeefee.com/category/extnet 然后跟着敲,去理解的. Ext.NET其实就是基于跨浏览器的ExtJS库和.NET Frame ...

  7. java解惑 读书笔记

    表达式之谜 >奇数性 当取余操作返回一个非0的结果.他与左操作数具有相同的正负符号. >找零谜题 在需要精确答案的地方,要避免使用float和double.对于货币运算.要使用int,lo ...

  8. UVA 12377 Number Coding --DFS

    题意:给一串数字,第一个数是Num的话,要使后面的数字组成Num个数,而且为不降的,将这Num个数分配到9个素因子上作为指数,问能组成多少个不同的数 解法:dfs一遍,看后面的数字能组成Num个不降数 ...

  9. bootstrap学习总结-css样式设计(二)

    首先,很感谢各位园友对我的支持,关于bootstrap的学习总结,我会持续更新,如果有写的不对的地方,麻烦各位给我指正出来哈.关于上篇文章,固定布局和流式布局很关键,如果还不太清楚的可以再看看我写的h ...

  10. JavaScript 中的原型声明和用法总结

    下面是自己写的一个关于js的拖拽的原型声明:代码如下 需要注意的问题包括: 1.this的指向到底是指向谁--弄清楚所指的对象 2.call()方法的使用 3.直接将父级原型赋给子级与使用for将其赋 ...