次の方法で共有


イメージ スケーラーのチュートリアル

この短いチュートリアルでは、.NET MAUI アプリで Image Scaler を使用するサンプルについて説明します。 開始するには、「はじめに」 ページ の手順を完了していることを確認します。.NET MAUI の場合。

イントロダクション

このサンプルでは、テキスト生成用の LanguageModel や画像スーパー解像度用の ImageScaler を含む一部の Windows AI API を使用して画像をスケーリングおよびシャープにする方法を示します。 [スケール] ボタンのいずれかをクリックしてイメージを拡大縮小するか (または元のスケーリングされていないイメージを再表示する)、テキスト プロンプトを入力して [生成] ボタンをクリックしてテキスト応答を生成します。

".NET MAUI アプリ" テンプレートからの変更は、次の 4 つのファイルに分割されます。

  1. MauiWindowsAISample.csproj: Windows AI API に必要な Windows App SDK パッケージ リファレンスを追加します。 このリファレンスは、Windows 用にビルドする場合にのみ条件付けする必要があります (詳細については、以下の追加の注意事項を参照してください)。 このファイルは、Windows に必要な TargetFramework も設定します。
  2. Platforms/Windows/MainPage.cs: 共有 MainPage クラスの部分メソッドを実装して、テキスト生成機能と画像スケーリング機能を表示および処理します。
  3. MainPage.xaml: テキスト生成と画像のスケーリングを表示するコントロールを定義します。
  4. MainPage.xaml.cs: Windows 固有のMainPage.csが実装する部分的なメソッドを定義します。

上記の 2 番目のファイルには、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. "release/experimental" ブランチに切り替えます。
  3. Samples/WindowsAIFoundry/cs-maui フォルダーに移動します。
  4. Visual Studio 2022 でMauiWindowsAISample.slnを開きます。
  5. デバッグ ツール バーにターゲット デバイスとして "Windows マシン" が設定されていることを確認します。
  6. F5 キーを押すか、[デバッグ] メニューから [デバッグの開始] を選択してサンプルを実行します (デバッグ メニューまたは Ctrl + F5 キーを押して [デバッグなしで開始] を選択して、デバッグなしでサンプルを実行することもできます)。

こちらも参照ください