Microsoft Agent Framework Microsoft.Extensions.AI Created: 01 Mar 2026 Updated: 01 Mar 2026

Text-to-Image Generation with IImageGenerator

IImageGenerator is the Microsoft.Extensions.AI abstraction for generating images from text prompts. It provides a unified API across different image generation providers and supports pipeline composition with middleware (logging, telemetry, caching). The interface is currently experimental and requires suppressing the MEAI001 diagnostic.

Key Concepts

1. Creating an IImageGenerator

Convert an OpenAI ImageClient to IImageGenerator using the AsIImageGenerator() extension method:

#pragma warning disable MEAI001
IImageGenerator generator = new OpenAIClient(apiKey)
.GetImageClient("dall-e-3")
.AsIImageGenerator();

2. GenerateImagesAsync — String Shortcut

The most concise way to generate an image. Pass a text prompt and an ImageGenerationOptions object. The response's Contents collection holds the generated DataContent items:

var options = new ImageGenerationOptions
{
ResponseFormat = ImageGenerationResponseFormat.Data // request binary data, not a URL
};

ImageGenerationResponse response = await generator.GenerateImagesAsync(prompt, options);
DataContent image = response.Contents.OfType<DataContent>().First();

File.WriteAllBytes("output.png", image.Data.ToArray());

Important: by default, DALL-E 3 returns a temporary URL (UriContent). Set ResponseFormat = ImageGenerationResponseFormat.Data to receive base64 binary data as DataContent instead.

3. ImageGenerationOptions

Customise the output with ImageGenerationOptions. Key properties:

  1. ResponseFormatData (binary), Uri (URL), or Hosted.
  2. ImageSize — pixel dimensions as System.Drawing.Size. Supported DALL-E 3 sizes: 1024x1024, 1792x1024, 1024x1792.
  3. Count — number of images to generate per request.
  4. MediaType — output MIME type; only supported by gpt-image-1, not DALL-E 3.
var wideOptions = new ImageGenerationOptions
{
ResponseFormat = ImageGenerationResponseFormat.Data,
ImageSize = new System.Drawing.Size(1792, 1024)
};

4. GenerateAsync — Direct Request API

For lower-level control, construct an ImageGenerationRequest and call GenerateAsync directly on the IImageGenerator:

var request = new ImageGenerationRequest("A chocolate lava cake on a slate plate...");
ImageGenerationResponse response = await generator.GenerateAsync(request, options);

Full Example

#pragma warning disable MEAI001
using Microsoft.Extensions.AI;
using OpenAI;

namespace MicrosoftAgentFrameworkLesson.ConsoleApp.TextToImage;

/// <summary>
/// Demonstrates IImageGenerator for text-to-image generation.
/// Scenario: Restaurant menu illustration generator — produces dish images
/// from descriptive prompts and saves them as PNG files.
/// </summary>
public static class TextToImageDemo
{
public static async Task RunAsync()
{
var apiKey = Environment.GetEnvironmentVariable("OPEN_AI_KEY")
?? throw new InvalidOperationException("Set OPEN_AI_KEY environment variable.");

Console.WriteLine("====== IImageGenerator — Restaurant Menu Illustrations ======\n");

IImageGenerator generator = new OpenAIClient(apiKey)
.GetImageClient("dall-e-3")
.AsIImageGenerator();

// -----------------------------------------------------------------------
// Demo 1: Basic image generation
// ResponseFormat.Data requests base64 binary so DataContent is populated.
// Without it the API returns a temporary URL (UriContent) instead.
// -----------------------------------------------------------------------
Console.WriteLine("--- Demo 1: Basic Image Generation ---");

string prompt1 = "A top-down food photography shot of a steaming bowl of " +
"truffle mushroom risotto on a rustic wooden table, " +
"garnished with fresh parsley and parmesan shavings, " +
"soft natural lighting, high-end restaurant style";

var basicOptions = new ImageGenerationOptions
{
ResponseFormat = ImageGenerationResponseFormat.Data
};

ImageGenerationResponse response1 = await generator.GenerateImagesAsync(prompt1, basicOptions);
DataContent image1 = response1.Contents.OfType<DataContent>().First();
string path1 = SaveImage(image1, "menu-risotto.png");
Console.WriteLine($"Saved: menu-risotto.png → {path1}");
Console.WriteLine();

// -----------------------------------------------------------------------
// Demo 2: Custom ImageGenerationOptions — wider aspect ratio
// ImageSize controls the pixel dimensions of the output image.
// Supported dall-e-3 sizes: 1024x1024, 1792x1024, 1024x1792.
// -----------------------------------------------------------------------
Console.WriteLine("--- Demo 2: ImageGenerationOptions (1792x1024, landscape) ---");

string prompt2 = "A wide restaurant hero shot of a seared salmon fillet " +
"with lemon butter sauce, asparagus spears and roasted cherry tomatoes, " +
"elegant white plate, bokeh background, professional food photography";

var wideOptions = new ImageGenerationOptions
{
ResponseFormat = ImageGenerationResponseFormat.Data,
ImageSize = new System.Drawing.Size(1792, 1024)
};

ImageGenerationResponse response2 = await generator.GenerateImagesAsync(prompt2, wideOptions);
DataContent image2 = response2.Contents.OfType<DataContent>().First();
string path2 = SaveImage(image2, "menu-salmon.png");
Console.WriteLine($"Saved: menu-salmon.png → {path2}");
Console.WriteLine();

// -----------------------------------------------------------------------
// Demo 3: ImageGenerationRequest — lower-level direct API call
// Construct an ImageGenerationRequest explicitly for more control.
// -----------------------------------------------------------------------
Console.WriteLine("--- Demo 3: ImageGenerationRequest (direct) ---");

var request3 = new ImageGenerationRequest("A decadent dark chocolate lava cake " +
"on a slate plate, warm molten chocolate flowing out, dusted with icing sugar, " +
"a scoop of vanilla ice cream melting beside it, moody dramatic lighting");

var options3 = new ImageGenerationOptions
{
ResponseFormat = ImageGenerationResponseFormat.Data,
ImageSize = new System.Drawing.Size(1024, 1024)
};

ImageGenerationResponse response3 = await generator.GenerateAsync(request3, options3);
DataContent image3 = response3.Contents.OfType<DataContent>().First();
string path3 = SaveImage(image3, "menu-lavacake.png");
Console.WriteLine($"Saved: menu-lavacake.png → {path3}");
Console.WriteLine();
}

private static string SaveImage(DataContent content, string fileName)
{
string dir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string path = Path.Combine(dir, fileName);
File.WriteAllBytes(path, content.Data.ToArray());
return Path.GetFullPath(path);
}
}
#pragma warning restore MEAI001
Share this lesson: