Windows Phone 開發——相機功能開發

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   strong   

原文: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方法,同時可以儲存到隔離儲存區 (Isolated Storage)空間中,方便以後讀取(如果僅僅儲存在相簿中,下次讀取時必須使用照片選取器讓使用者去選擇照片):
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();            }        }

 

儲存照片有兩個方法:SavePicture和SavePictureToCameraRoll,前面的方法是儲存到照片中心“儲存的照片”中,後一種方法是儲存到“本機拍照”中。

 

  1. 對於閃光燈、對焦、解析度以及快門都有相應的方法,從上面的代碼中也可以看到快門有半按、全按、釋放等事件,這裡不再贅述,可以從原始碼中看到相關的事件。

 

這個例子的demo是微軟提供的,比較詳細,源碼如下:http://pan.baidu.com/s/1c0rIqSK

 

參考文章:Windows Phone 的相機和照片

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.