共用方式為


使用 Windows 內建相機用戶介面在桌面應用程式中擷取相片和影片

本文說明如何使用 CameraCaptureUI 類別,使用 Windows 內建的相機 UI 來擷取相片或視訊。 這項功能可讓您的應用程式使用幾行程式代碼來取得使用者擷取的相片或視訊。

如果您想要提供自己的相機 UI,或您的案例需要更健全、低階的擷取作業控制,則您應該使用 MediaCapture 類別,並實作您自己的擷取體驗。 如需詳細資訊,請參閱使用 MediaCapture 基本相片、視訊和音訊擷取

請注意,UWP app 不支援 Microsoft.Windows.Media.Capture 命名空間中的 CameraCaptureUI 類別。 如需使用此功能 UWP 版本的詳細資訊,請參閱 使用 Windows 內建相機 UI 在 UWP 應用程式中擷取相片和視訊

使用 CameraCaptureUI 類別來擷取相片

建立 CameraCaptureUI 的新實例,傳入應用程式視窗 的 AppWindow.Id 屬性。 PhotoSettings 屬性可讓您指定所擷取相片的某些條件約束,包括檔格式和解析度上限,以及 UI 是否允許使用者在擷取相片之後裁剪相片。 VideoSettings 屬性提供類似的影片擷取屬性,例如最大解析度和持續時間,以及 UI 是否允許使用者在擷取影片之後修剪影片。

呼叫 CaptureFileAsync 以異步方式啟動相機擷取 UI。 使用 CameraCaptureUIMode 中的其中一個值來指定 UI 是否應該允許相片擷取、視訊擷取或兩者。 當 CaptureFileAsync 完成時,它會傳回包含所擷取相片或視訊的 StorageFile 檔案物件。 如果傳回的物件為 Null,表示使用者取消擷取作業或發生錯誤。

下列範例示範如何啟動 CameraCaptureUI 以進行相片擷取,並將影像格式指定為 PNG 並停用裁剪。 在此範例中,擷取的相片會設定為 Image 控件的來源。

var cameraCaptureUI = new CameraCaptureUI(this.AppWindow.Id);
cameraCaptureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Png;
cameraCaptureUI.PhotoSettings.AllowCropping = false;

// Capture a photo asynchronously
StorageFile photo = await cameraCaptureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

if (photo != null)
{
    // Photo capture was successful

    // Show the captured photo in a XAML Image control  
    using (IRandomAccessStream fileStream = await photo.OpenAsync(Windows.Storage.FileAccessMode.Read))
    {
        // Set the image source to the selected bitmap 
        BitmapImage bitmapImage = new BitmapImage();
        await bitmapImage.SetSourceAsync(fileStream);
        iCapturedImage.Source = bitmapImage;
    }
} else
{
    // Photo capture failed or was cancelled
}

使用 CameraCaptureUI 類別來擷取影片

下列範例示範如何啟動 CameraCaptureUI 以進行視訊擷取,並將視訊上限指定為標準定義,並停用修剪。 在此範例中,擷取的相片會設定為 MediaPlayerElement 控制件的來源。

var cameraCaptureUI = new CameraCaptureUI(this.AppWindow.Id);
cameraCaptureUI.VideoSettings.MaxResolution = CameraCaptureUIMaxVideoResolution.StandardDefinition;
cameraCaptureUI.VideoSettings.AllowTrimming = true;
StorageFile videoFile = await cameraCaptureUI.CaptureFileAsync(CameraCaptureUIMode.Video);

if (videoFile != null)
{
    // Video capture was successful

    // Show the captured video in a MediaPlayerElement control
    mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(videoFile);
    mediaPlayerElement.MediaPlayer.Play();
}
else
{
    // Video capture failed or was cancelled
}

移動和重新命名擷取的媒體檔案

CameraCaptureUI 會建立所擷取媒體檔案的隨機名稱,因此您可能想要重新命名和移動擷取的檔案,使其保持組織。 下列範例會移動並重新命名擷取的檔案。

StorageFile photo = await cameraCaptureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

if (photo != null)
{
    // Move and rename captured photo
    StorageFolder destinationFolder =
    await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePhotoFolder",
        CreationCollisionOption.OpenIfExists);

    await photo.CopyAsync(destinationFolder, "ProfilePhoto.jpg", NameCollisionOption.ReplaceExisting);
    await photo.DeleteAsync();
}