Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Tutorial singkat ini akan memandu Anda melalui sampel yang menggunakan Image Scaler di aplikasi .NET MAUI. Untuk memulai, pastikan Anda telah menyelesaikan langkah-langkah di halaman Memulai. untuk .NET MAUI.
Pendahuluan
Sampel ini menunjukkan penggunaan beberapa API AI Windows, termasuk LanguageModel untuk pembuatan teks dan ImageScaler untuk resolusi super gambar untuk menskalakan dan mempertajam gambar. Klik salah satu tombol "Skala" untuk menskalakan gambar (atau munculkan kembali gambar asli yang tidak diskalakan), atau masukkan perintah teks dan klik tombol "Hasilkan" untuk menghasilkan respons teks.
Perubahan dari templat ".NET MAUI App" dibagi menjadi empat file:
- MauiWindowsAISample.csproj: Menambahkan referensi paket Windows App SDK yang diperlukan untuk API Windows AI. Referensi ini perlu dikondisikan hanya saat mengompilasi untuk Windows (lihat Catatan Tambahan di bawah ini untuk rinciannya). File ini juga mengatur TargetFramework yang diperlukan untuk Windows.
- Platform/Windows/MainPage.cs: Menerapkan metode parsial dari kelas MainPage bersama untuk menampilkan dan menangani fungsionalitas pembuatan teks dan penskalaan gambar.
- MainPage.xaml: Menentukan kontrol untuk menampilkan pembuatan teks dan penskalaan gambar.
- MainPage.xaml.cs: Menentukan metode parsial yang diterapkan MainPage.cs khusus Windows.
Dalam file kedua yang tercantum di atas, Anda akan menemukan fungsi berikut, yang menunjukkan beberapa fungsionalitas dasar untuk metode 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());
}
}
}
}
Bangun dan jalankan sampel
- Klon repositori WindowsAppSDK-Samples.
- Beralih ke branch "release/experimental".
- Navigasikan ke folder Samples/WindowsAIFoundry/cs-maui .
- Buka MauiWindowsAISample.sln di Visual Studio 2022.
- Pastikan toolbar debug memiliki "Windows Machine" yang ditetapkan sebagai perangkat target.
- Tekan F5 atau pilih "Mulai Penelusuran Kesalahan" dari menu Debug untuk menjalankan contoh uji coba (contoh uji coba juga dapat dijalankan tanpa penelusuran kesalahan dengan memilih "Mulai Tanpa Penelusuran Kesalahan" dari menu Debug atau Ctrl+F5).