Compartir a través de


Tutorial del escalador de imágenes

Este breve tutorial le guiará a través de un ejemplo que usa Image Scaler en una aplicación MAUI de .NET. Para empezar, asegúrese de que ha completado los pasos descritos en la página Introducción. para .NET MAUI.

Introducción

En este ejemplo se muestra el uso de algunas API de inteligencia artificial de Windows, incluido LanguageModel para la generación de texto y ImageScaler para la super resolución de imágenes para escalar y afilar imágenes. Haga clic en uno de los botones "Escalar" para escalar la imagen (o volver a mostrar la imagen original, sin escalar), o escriba un mensaje de texto y haga clic en el botón "Generar" para generar una respuesta de texto.

Los cambios de la plantilla ".NET MAUI App" se dividen en cuatro archivos:

  1. MauiWindowsAISample.csproj: agrega la referencia del paquete de Windows App SDK necesaria para las API de IA de Windows. Esta referencia solo debe estar condicionada al compilar para Windows (consulte Notas adicionales a continuación para obtener más información). Este archivo también establece el targetFramework necesario para Windows.
  2. Plataformas/Windows/MainPage.cs: implementa métodos parciales de la clase MainPage compartida para mostrar y controlar la funcionalidad de generación de texto e escalado de imágenes.
  3. MainPage.xaml: define controles para mostrar la generación de texto y el escalado de imágenes.
  4. MainPage.xaml.cs: define métodos parciales que implementa el MainPage.cs específico de Windows.

En el segundo archivo enumerado anteriormente, encontrará la siguiente función, que muestra algunas funcionalidades básicas para el método 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());
            }
        }
    }
}

Compilar y ejecutar el ejemplo

  1. Clone el repositorio WindowsAppSDK-Samples .
  2. Cambie a la rama "release/experimental".
  3. Vaya a la carpeta Samples/WindowsAIFoundry/cs-maui .
  4. Abra MauiWindowsAISample.sln en Visual Studio 2022.
  5. Asegúrese de que la barra de herramientas de depuración tiene "Máquina Windows" establecida como dispositivo de destino.
  6. Presione F5 o seleccione "Iniciar depuración" en el menú Depurar para ejecutar el ejemplo (el ejemplo también se puede ejecutar sin depurar seleccionando "Iniciar sin depurar" en el menú Depurar o Ctrl+F5).

Consulte también