Windows Phone 开发——相机功能开发

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

  相机功能是手机区别于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[4096];

                        int bytesRead = -1;

 

                        // Copy the thumbnail to isolated storage.

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

                        {

                            targetStream.Write(readBuffer, 0, 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();

            }

        }

 

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

 

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

 

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

 

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

目录
相关文章
|
11天前
|
存储 文字识别 C#
.NET开源免费、功能强大的 Windows 截图录屏神器
今天大姚给大家分享一款.NET开源免费(基于GPL3.0开源协议)、功能强大、简洁灵活的 Windows 截图、录屏、Gif动图制作神器:ShareX。
|
1月前
|
Windows
Windows 命令提示符(CMD)操作(七):扩展命令和功能
Windows 命令提示符(CMD)操作(七):扩展命令和功能
42 0
|
1月前
|
Windows
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
|
1月前
|
数据可视化 数据库 C++
Qt 5.14.2揭秘高效开发:如何用VS2022快速部署Qt 5.14.2,打造无与伦比的Windows应用
Qt 5.14.2揭秘高效开发:如何用VS2022快速部署Qt 5.14.2,打造无与伦比的Windows应用
|
2月前
|
C# Windows
.NET开源的一个小而快并且功能强大的 Windows 动态桌面软件
.NET开源的一个小而快并且功能强大的 Windows 动态桌面软件
|
3月前
|
存储 网络协议 安全
Windows Server 2022 安全功能重大更新
这篇文将介绍 Windows Server 2022 中的一些新增的安全功能,在 Windows Server 2019 的强大基础之上引入了许多创新功能。
60 0
|
12天前
|
监控 安全 API
7.3 Windows驱动开发:内核监视LoadImage映像回调
在笔者上一篇文章`《内核注册并监控对象回调》`介绍了如何运用`ObRegisterCallbacks`注册`进程与线程`回调,并通过该回调实现了`拦截`指定进行运行的效果,本章`LyShark`将带大家继续探索一个新的回调注册函数,`PsSetLoadImageNotifyRoutine`常用于注册`LoadImage`映像监视,当有模块被系统加载时则可以第一时间获取到加载模块信息,需要注意的是该回调函数内无法进行拦截,如需要拦截则需写入返回指令这部分内容将在下一章进行讲解,本章将主要实现对模块的监视功能。
29 0
7.3 Windows驱动开发:内核监视LoadImage映像回调
|
4月前
|
监控 安全 API
7.2 Windows驱动开发:内核注册并监控对象回调
在笔者上一篇文章`《内核枚举进程与线程ObCall回调》`简单介绍了如何枚举系统中已经存在的`进程与线程`回调,本章`LyShark`将通过对象回调实现对进程线程的`句柄`监控,在内核中提供了`ObRegisterCallbacks`回调,使用这个内核`回调`函数,可注册一个`对象`回调,不过目前该函数`只能`监控进程与线程句柄操作,通过监控进程或线程句柄,可实现保护指定进程线程不被终止的目的。
29 0
7.2 Windows驱动开发:内核注册并监控对象回调
|
4月前
|
监控 安全 API
7.6 Windows驱动开发:内核监控FileObject文件回调
本篇文章与上一篇文章`《内核注册并监控对象回调》`所使用的方式是一样的都是使用`ObRegisterCallbacks`注册回调事件,只不过上一篇博文中`LyShark`将回调结构体`OB_OPERATION_REGISTRATION`中的`ObjectType`填充为了`PsProcessType`和`PsThreadType`格式从而实现监控进程与线程,本章我们需要将该结构填充为`IoFileObjectType`以此来实现对文件的监控,文件过滤驱动不仅仅可以用来监控文件的打开,还可以用它实现对文件的保护,一旦驱动加载则文件是不可被删除和改动的。
29 1
7.6 Windows驱动开发:内核监控FileObject文件回调
|
4月前
|
监控 安全 API
6.9 Windows驱动开发:内核枚举进线程ObCall回调
在笔者上一篇文章`《内核枚举Registry注册表回调》`中我们通过特征码定位实现了对注册表回调的枚举,本篇文章`LyShark`将教大家如何枚举系统中的`ProcessObCall`进程回调以及`ThreadObCall`线程回调,之所以放在一起来讲解是因为这两中回调在枚举是都需要使用通用结构体`_OB_CALLBACK`以及`_OBJECT_TYPE`所以放在一起来讲解最好不过。
41 1
6.9 Windows驱动开发:内核枚举进线程ObCall回调