共用方式為


開始使用 AI 影像生成

Microsoft Foundry 在 Windows 上支援 AI 影像生成功能,透過一組人工智慧支援、Stable Diffusion(用於處理影像的開源 AI 模型)API 支援,這些 API 隨 Windows 應用程式 SDK 內建。 這些 API 可用於你的 Windows 應用程式,利用自然語言提示和裝置生成模型來創建、轉換及增強影像與照片。

AI 影像生成在 Windows Copilot+ PC 上優化了效率與效能。

如需 API 詳細數據,請參閱 適用於 AI 映像功能的 API 參考

先決條件

我可以用 AI 影像生成做什麼?

利用 AI 影像生成將提示轉化為視覺圖像。 支援的功能包括:

  • 文字轉影像

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

  • 圖像對圖像

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

  • 魔法填充

    用 AI 生成的內容填滿影像中遮罩區域。 對於移除物件、修復區域以及直覺式編輯(透過文字提示而非手動工具進行複雜修訂)非常有用。

  • 著色書風格

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

  • 重新設計

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

範例

使用 AI 影像生成 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 參數生成影像

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

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 = TextContentFilterSeverity(SeverityLevel.Low);
    contentFilterOptions.ImageMaxAllowedSeverityLevel = ImageContentFilterSeverity(SeverityLevel.Minimium);
    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}");
    }
}

負責任的人工智慧

我們已使用下列步驟的組合,以確保這些映像 API 值得信任、安全且負責任地建置。 建議您檢閱在應用程式中實作 AI 功能時,在 Windows 上負責任產生 AI 開發 中所述的最佳做法。

另請參閱