本教程将指导你完成在 .NET MAUI 应用中使用图像缩放程序的示例。 请确保已完成.NET MAUI入门页面中的步骤,以便开始。
介绍
此示例演示如何使用一些 Windows AI API,包括用于文本生成的 LanguageModel,以及图像超分辨率的 ImageScaler 来缩放和锐化图像。 单击其中一个“缩放”按钮缩放图像(或重新显示原始、未缩放的图像),或输入文本提示,然后单击“生成”按钮以生成文本响应。
“.NET MAUI 应用”模板的更改拆分为四个文件:
- MauiWindowsCopilotRuntimeSample.csproj:添加所需的 Windows 应用 SDK 包引用,以支持 Windows AI API。 仅当为 Windows 生成时,才需要对该引用施加条件(有关详细信息,请参阅下文的附加说明)。 此文件还设置 Windows 所需的 TargetFramework。
- 平台/Windows/MainPage.cs:实现共享 MainPage 类中的分部方法,以显示和处理文本生成和图像缩放功能。
- MainPage.xaml:定义用于显示文本生成和图像缩放的控件。
- 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());
}
}
}
}
生成和运行示例
- 将 存储库 克隆到 Copilot+PC。
- 在 Visual Studio 2022 中打开解决方案文件MauiWindowsCopilotRuntimeSample.sln。
- 确保调试工具栏已将“Windows 计算机”设置为目标设备。
- 按 F5 或从“调试”菜单中选择“开始调试”以运行示例。 注意:也可以通过从“调试”菜单或 Ctrl+F5 中选择“启动而不调试”来运行该示例。