開始使用影像生成

Windows 版的 Microsoft Foundry 支援透過 Windows 應用程式 SDK 內建的由 Stable Diffusion 提供技術支援的 API 生成映像檔。 你可以在 Windows 應用程式中使用這些 API,利用自然語言提示和裝置上的生成模型來創建、轉換和增強圖片與照片。

影像生成經過優化,以提升 Windows Copilot+ PCs 上的效率與效能。

關於 API 細節,請參閱影像 API 參考。

AI 開發者畫廊讓你可以嘗試提示、檢視範例原始碼,並在將影像生成整合進應用程式前匯出一個可運作的 Visual Studio 專案。

這很重要

套件資訊清單需求:若要使用 Windows AI 影像處理 API,您的應用程式必須封裝為 MSIX 套件,並在您的systemAIModels中聲明 Package.appxmanifest 功能。 此外,請確保您的清單的 MaxVersionTested 屬性設定為最新的 Windows 版本(例如, 10.0.26226.0 或更高版本),以正確支援 Windows AI 功能。 使用較舊的值可能會導致載入模型時「未由應用程式宣告」錯誤。

<Dependencies>
  <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.26226.0" />
  <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.26226.0" />
</Dependencies>

先決條件

  • Windows 版本: Windows 11,版本 24H2(版本 26100)或更新版本
  • Windows 應用程式 SDK 版本:Version 2.0 Experimental
  • Hardware: Copilot+ PC,附有 NPU(必備)

支援的硬體

影像產生可在以下硬體上運行:

Hardware Status 詳細資料
NPU(Copilot+ PC) ✅ 可取得 這是唯一支援的硬體路徑。 請參考 Copilot+ PCs 開發者指南。
GPU ❌ 未支援 GPU 上沒有。
CPU ❌ 未支援 CPU 上沒有。

型號可用性與下載

AI 影像生成模型在 Copilot+ PC 上是optional — 預設為 未預裝,因為安裝容量為數 GB。 當你的應用程式第一次呼叫 EnsureReadyAsync時,模型會透過 Windows Update 在背景下載。 終端使用者也可以在之後移除該型號以回收磁碟空間。

這種行為與其他大型可選 Windows AI 模型的生命週期相符——你的應用程式必須明確處理「尚未安裝」的情況,而不是假設模型已經存在。

由於 AI 影像生成模型體積龐大且預設不存在,致電前EnsureReadyAsync請顯示確認對話框,讓使用者同意儲存費用與背景下載。 一個典型的模式:

  1. 呼叫 GetReadyState,並根據傳回的 AIFeatureReadyState 進行分支處理:

    • Ready — 模型安裝完成;繼續。
    • NotReady 或者 EnsureNeeded — 顯示你的同意對話框(見下文),只有在用戶同意時才撥打 EnsureReadyAsync 電話。
    • NotSupportedOnCurrentSystem — 該裝置並非Copilot+ PC,或不符合支援硬體的要求。 提供備用體驗,並在適當時揭示硬體需求,讓使用者能做出明智的升級決策。
  2. 在你的同意對話框中,請說明:

    • 可選的影像生成模型將被下載(數 GB 儲存空間)。
    • 下載是在背景透過 Windows Update 進行的。
    • 使用者可在 Settings>Windows Update 監控下載進度。
    • 使用者若不再需要,可以在設定>>系統 AI 元件中移除該模型。

    Tip

    在面向使用者的字串(對話文字、狀態訊息)中,將模型稱為「影像生成模型」或「可選 AI 模型」,而非「SDXL」或「穩定擴散」。大多數終端使用者對底層型號名稱並不熟悉,通用術語能更清楚地傳達目的。

  3. 在 EnsureReadyAsync 進行期間,請在您的應用程式中顯示進度指示器。 請參考 Get Start with Windows AI APIS 來了解載入介面的模式。

模型安裝後

模型會一直留在裝置上,直到使用者移除為止。 使用者可在設定>>系統 AI 元件中管理已安裝的模型,包括 AI 影像生成模型。 如果使用者之後移除該模型,您的應用程式下一次呼叫 GetReadyState 時會傳回 NotReady 或 EnsureNeeded,並且應重新執行同意與下載流程。

選擇影像生成工作流程

利用影像生成將提示轉化為視覺成品。 支援的工作流程包括:

  • 文字轉影像

    從描述性文字提示生成圖片。 適合插畫、設計、客製化背景及概念視覺化。

  • 圖像對圖像

    根據文字指引轉換現有影像,同時保留結構。 適合樣式設計、主題設定及其他變化。

  • 魔法填充

    用模型生成的內容填滿遮罩區域。 使用此工作流程移除物件、修復區域,或透過文字提示進行針對性編輯。

  • 著色書風格

    將圖片轉換成簡化的輪廓,可用於著色書或類似的教育體驗。

  • 重新設計

    在保留結構的同時,將藝術或視覺風格應用於現有影像。 適合創意濾鏡、藝術模式或主題變換。

使用影像生成 API

使用影像生成 API 時,請遵循以下基本步驟。

  1. 請使用 EnsureReadyAsync 確保模型已準備好。
  2. 建立一個 ImageGenerator 實例。
  3. 選擇適當的生成工作流程(文字提示、圖片輸入或遮罩)。
  4. 呼叫相應的生成方法。
  5. 接收輸出為影像 緩衝 區,供觀看、編輯或儲存。

從文字提示生成圖片(文字對圖片)

這個範例展示了如何從文字提示產生圖片。 具體來說,是「山湖上的美麗夕陽」。

using Microsoft.Windows.AI.Imaging;
using Microsoft.Graphics.Imaging;

public async Task GenerateImageFromText()
{
    // Check if models are ready
    var readyState = ImageGenerator.GetReadyState();
    if (readyState != AIFeatureReadyState.Ready)
    {
        // Download models if needed
        var result = await ImageGenerator.EnsureReadyAsync();
        if (result.Status != AIFeatureReadyResultState.Success)
        {
            Console.WriteLine("Failed to prepare models");
            return;
        }
    }

    // Create ImageGenerator instance
    using var generator = await ImageGenerator.CreateAsync();
    
    // Configure generation options
    var options = new ImageGenerationOptions
    {
        MaxInferenceSteps = 6,
        Creativity = 0.8,
        Seed = 42
    };

    // Generate image
    var result = generator.GenerateImageFromTextPrompt("A beautiful sunset over a mountain lake", options);
    
    if (result.Status == ImageGeneratorResultStatus.Success)
    {
        var imageBuffer = result.Image;
        // Use the generated image (save to file, display, etc.)
        await SaveImageBufferAsync(imageBuffer, "generated_image.png");
    }
    else
    {
        Console.WriteLine($"Image generation failed: {result.Status}");
    }
}

轉換影像風格(圖像轉圖像)

這個範例展示了如何根據文字提示將一張照片轉換成油畫。 特別是「油畫風格、粗筆觸、具有藝術感」。

public async Task RestyleImage()
{
    using var generator = await ImageGenerator.CreateAsync();
    
    // Load input image
    var inputImage = await LoadImageBufferAsync("photo.jpg");
    
    var options = new ImageGenerationOptions();
    var styleOptions = new ImageFromImageGenerationOptions
    {
        Style = ImageFromImageGenerationStyle.Restyle,
        ColorPreservation = 0.7f
    };

    var result = generator.GenerateImageFromImageBuffer(
        inputImage, 
        "oil painting style, thick brush strokes, artistic", 
        options, 
        styleOptions);
    
    if (result.Status == ImageGeneratorResultStatus.Success)
    {
        await SaveImageBufferAsync(result.Image, "restyled_image.png");
    }
}

轉換影像風格(影像對影像複合體)

這個範例展示了如何根據文字提示將一張照片轉換成油畫。 具體來說,是「油畫、厚重筆觸、豐富的色彩調色盤、傳統畫布質感、寫實光線、古典美術風格、層疊顏料、高細節、戲劇性對比、厚塗、質感畫布」。

using Microsoft.Windows.AI.Imaging;

public async Task CreateImageFromPrompt()
{
    using ImageGenerator model = await ImageGenerator.CreateAsync();

    // Using default values
    var options = new ImageGenerationOptions();

    // Set ImageFromImageGenerationOptions fields
    var imageFromImageOptions = new ImageFromImageGenerationOptions();
    imageFromImageOptions.Style = ImageFromImageGenerationStyle.Restyle;
    imageFromImageOptions.ColorPreservation = 0.5f; // range [0.0f, 1.0f]

    // Load an input image buffer
    using var inputImage = await Utils.LoadSampleImageBufferAsync("sdxl_input_horse.png");

    var textPrompt = "An oil painting, thick brush strokes, rich color palette, traditional canvas texture, realistic lighting, classical fine art style, layered paint, high detail, dramatic contrast, impasto, textured canvas";

    var result = model.GenerateImageFromImageBuffer(inputImage, textPrompt, options, imageFromImageOptions);
    if (result.Status == ImageGeneratorResultStatus.Success)
    {
        // Image generated successfully
        var imageBuffer = result.Image;
        // Process the imageBuffer as needed, e.g., save to file or display
    }
    else
    {
        // Handle error cases based on result.Status
        Console.WriteLine($"Image generation failed with status: {result.Status}");
    }
}

魔法填充面具

這個範例展示了如何使用遮罩來填補影像的某個區域。 具體來說,是「一輛紅色跑車」。

public async Task FillMaskedRegion()
{
    using var generator = await ImageGenerator.CreateAsync();
    
    var inputImage = await LoadImageBufferAsync("scene.jpg");
    var maskImage = await LoadImageBufferAsync("mask.png"); // GRAY8 format
    
    var options = new ImageGenerationOptions();
    
    var result = generator.GenerateImageFromImageBufferAndMask(
        inputImage, 
        maskImage, 
        "a red sports car", 
        options);
    
    if (result.Status == ImageGeneratorResultStatus.Success)
    {
        await SaveImageBufferAsync(result.Image, "filled_image.png");
    }
}

產生著色書風格的圖片

這個範例展示了如何用著色書風格產生圖像。 具體來說,是「太空船裡的貓」。

using Microsoft.Windows.AI.Imaging;

public async Task CreateImageFromPrompt()
{
    using ImageGenerator model = await ImageGenerator.CreateAsync();

    // Using default values
    var options = new ImageGenerationOptions();

    // Set ImageFromTextGenerationOptions fields
    var imageFromTextOptions = new ImageFromTextGenerationOptions();
    imageFromTextOptions.Style = ImageFromTextGenerationStyle.ColoringBook;

    var result = model.GenerateImageFromTextPrompt("Cat in spaceship", options, imageFromTextOptions);
    if (result.Status == ImageGeneratorResultStatus.Success)
    {
        // Image generated successfully
        var imageBuffer = result.Image;
        // Process the imageBuffer as needed, e.g., save to file or display
    }
    else
    {
        // Handle error cases based on result.Status
        Console.WriteLine($"Image generation failed with status: {result.Status}");
    }
}

使用自訂的 ImageGenerationOptions 參數生成影像

這個範例展示了如何根據一組內容過濾器和限制生成圖片。 具體來說,是用 TextContentFilterSeverity 為 Low 和 ImageContentFilterSeverity 為 Minimum 的「太空船裡的貓」。

using Microsoft.Windows.AI.Imaging;
using Microsoft.Windows.AI.ContentSafety;

public async Task CreateImageFromPromptAndCustomOptions()
{
    using ImageGenerator model = await ImageGenerator.CreateAsync();

    // Using default values
    var options = new ImageGenerationOptions();

    // Set custom ImageGenerationOptions fields
    options.MaxInferenceSteps = 6;
    options.Creativity = 0.8;
    options.Seed = 1234;
    ContentFilterOptions contentFilterOptions = new ContentFilterOptions();
    contentFilterOptions.PromptMaxAllowedSeverityLevel = new TextContentFilterSeverity { Hate = SeverityLevel.Low, Sexual = SeverityLevel.Low, Violent = SeverityLevel.Low, SelfHarm = SeverityLevel.Low };
    contentFilterOptions.ImageMaxAllowedSeverityLevel = new ImageContentFilterSeverity { AdultContentLevel = SeverityLevel.Minimum, GoryContentLevel = SeverityLevel.Minimum, RacyContentLevel = SeverityLevel.Minimum, ViolentContentLevel = SeverityLevel.Minimum };
    options.ContentFilterOptions = contentFilterOptions;

    var result = model.GenerateImageFromTextPrompt("Cat in spaceship", options);
    if (result.Status == ImageGeneratorResultStatus.Success)
    {
        // Image generated successfully
        var imageBuffer = result.Image;
        // Process the imageBuffer as needed, e.g., save to file or display
    }
    else
    {
        // Handle error cases based on result.Status
        Console.WriteLine($"Image generation failed with status: {result.Status}");
    }
}

負責任的人工智慧

在使用 Windows 應用程式修改或生成圖片時,請遵循負責任的 AI 建議,包括透明度與使用者信任。 為協助使用者了解生成或修改影像的來源與歷史,請依據 內容來源與真實性聯盟(C2PA) 標準提供內容憑證。

請參閱 Windows 上負責任的生成式 AI 開發,了解在 Windows 應用程式中加入生成式影像功能的最佳實務。

另請參閱