共用方式為


影像縮放器指南

這個簡短的教學課程將逐步引導您完成在 .NET MAUI 應用程式中使用影像縮放器的範例。 若要開始,請確定您已完成 [ 用戶入門] 頁面中的步驟。 適用於 .NET MAUI。

簡介

此範例示範使用一些 Windows AI API,包括用於文字產生的 LanguageModel,以及影像超解析度的 ImageScaler 來縮放和銳化影像。 按兩下其中一個 [調整] 按鈕來縮放影像(或重新顯示原始、未調整的影像),或輸入文字提示,然後按兩下 [產生] 按鈕以產生文字回應。

來自 “.NET MAUI App” 範本的修改會分散到四個檔案:

  1. MauiWindowsAISample.csproj:新增 Windows AI API 所需的 Windows 應用程式 SDK 套件參考。 只有在為 Windows 建置時,才需要設定此參考條件(如需詳細資訊,請參閱下方的其他附注)。 此檔案也會設定 Windows 的所需 TargetFramework。
  2. 平臺/Windows/MainPage.cs:實作來自共用MainPage類別的部分方法,以顯示及處理文字產生和影像縮放功能。
  3. MainPage.xaml:定義控件以顯示文字產生和影像縮放。
  4. MainPage.xaml.cs:定義 Windows 特定的 MainPage.cs 實作的部分方法。

在上述第二個檔案中,您會發現下列函式,其中示範 ImageScaler 方法的一些基本功能:

private async void DoScaleImage(double scale)
{
    // Load the original image
    var resourceManager = new Microsoft.Windows.ApplicationModel.Resources.ResourceManager();
    var resource = resourceManager.MainResourceMap.GetValue("ms-resource:///Files/enhance.png");
    if (resource.Kind == Microsoft.Windows.ApplicationModel.Resources.ResourceCandidateKind.FilePath)
    {
        // Load as a SoftwareBitmap
        var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(resource.ValueAsString);
        var fileStream = await file.OpenStreamForReadAsync();

        var decoder = await BitmapDecoder.CreateAsync(fileStream.AsRandomAccessStream());
        var softwareBitmap = await decoder.GetSoftwareBitmapAsync();
        int origWidth = softwareBitmap.PixelWidth;
        int origHeight = softwareBitmap.PixelHeight;

        SoftwareBitmap finalImage;
        if (scale == 0.0)
        {
            // just show the original image
            finalImage = softwareBitmap;
        }
        else
        {
            // Scale the image to be the exact pixel size of the element displaying it
            if (ImageScaler.GetReadyState() == AIFeatureReadyState.NotReady)
            {
                var op = await ImageScaler.EnsureReadyAsync();
                if (op.Status != AIFeatureReadyResultState.Success)
                {
                    throw new Exception(op.ExtendedError.Message);
                }
            }

            ImageScaler imageScaler = await ImageScaler.CreateAsync();

            double imageScale = scale;
            if (imageScale > imageScaler.MaxSupportedScaleFactor)
            {
                imageScale = imageScaler.MaxSupportedScaleFactor;
            }
            System.Diagnostics.Debug.WriteLine($"Scaling to {imageScale}x...");

            int newHeight = (int)(origHeight * imageScale);
            int newWidth = (int)(origWidth * imageScale);
            finalImage = imageScaler.ScaleSoftwareBitmap(softwareBitmap, newWidth, newHeight);
        }

        // Display the scaled image. The if/else here shows two different approaches to do this.
        var mauiContext = scaledImage.Handler?.MauiContext;
        if (mauiContext != null)
        {
            // set the SoftwareBitmap as the source of the Image control
            var imageToShow = finalImage;
            if (imageToShow.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                imageToShow.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                // SoftwareBitmapSource only supports Bgra8 and doesn't support Straight alpha mode, so convert
                imageToShow = SoftwareBitmap.Convert(imageToShow, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }
            var softwareBitmapSource = new SoftwareBitmapSource();
            _ = softwareBitmapSource.SetBitmapAsync(imageToShow);
            var nativeScaledImageView = (Microsoft.UI.Xaml.Controls.Image)scaledImage.ToPlatform(mauiContext);
            nativeScaledImageView.Source = softwareBitmapSource;
        }
        else
        {
            // An alternative approach is to encode the image so a stream can be handed
            // to the Maui ImageSource.

            // Note: There's no "using(...)" here, since this stream needs to be kept alive for the image to be displayed
            var scaledStream = new InMemoryRandomAccessStream();
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, scaledStream);
                encoder.SetSoftwareBitmap(finalImage);
                await encoder.FlushAsync();
                scaledImage.Source = ImageSource.FromStream(() => scaledStream.AsStream());
            }
        }
    }
}

建置並執行範例

  1. 複製 WindowsAppSDK-Samples 存放庫。
  2. 切換至 「發行/實驗性」分支。
  3. 流覽至 Samples/WindowsAIFoundry/cs-maui 資料夾。
  4. 在 Visual Studio 2022 中開啟 MauiWindowsAISample.sln。
  5. 確定偵錯工具列已將 [Windows 計算機] 設定為目標裝置。
  6. 按 F5 或從 [偵錯] 選單選取 [開始偵錯],以執行範例(您也可以從 [偵錯] 功能表或 Ctrl+F5 選取 [啟動但不偵錯] 來執行範例。

另請參閱