Skip to content

Commit fa1e559

Browse files
authored
Add tutorial for text-to-image generation using Microsoft.Extensions.AI (#49391)
1 parent 31f3ee2 commit fa1e559

File tree

11 files changed

+224
-23
lines changed

11 files changed

+224
-23
lines changed

docs/ai/index.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ landingContent:
3535
url: quickstarts/prompt-model.md
3636
- text: Build an Azure AI chat app
3737
url: quickstarts/build-chat-app.md
38-
- text: Generate images using Azure AI
39-
url: quickstarts/generate-images.md
38+
- text: Generate images from text
39+
url: quickstarts/text-to-image.md
4040

4141
# Card
4242
- title: Essential concepts

docs/ai/overview.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,10 @@ We recommend the following sequence of tutorials and articles for an introductio
3636
| Scenario | Tutorial |
3737
|-----------------------------|-------------------------------------------------------------------------|
3838
| Create a chat application | [Build an Azure AI chat app with .NET](./quickstarts/build-chat-app.md) |
39-
| Summarize text | [Summarize text using Azure AI chat app with .NET](./quickstarts/prompt-model.md) |
40-
| Chat with your data | [Get insight about your data from an .NET Azure AI chat app](./quickstarts/build-vector-search-app.md) |
39+
| Summarize text | [Summarize text using Azure AI chat app](./quickstarts/prompt-model.md) |
40+
| Chat with your data | [Get insight about your data from a .NET Azure AI chat app](./quickstarts/build-vector-search-app.md) |
4141
| Call .NET functions with AI | [Extend Azure AI using tools and execute a local function with .NET](./quickstarts/use-function-calling.md) |
42-
| Generate images | [Generate images using Azure AI with .NET](./quickstarts/generate-images.md) |
42+
| Generate images | [Generate images from text](./quickstarts/text-to-image.md) |
4343
| Train your own model | [ML.NET tutorial](https://dotnet.microsoft.com/learn/ml-dotnet/get-started-tutorial/intro) |
4444

4545
Browse the table of contents to learn more about the core concepts, starting with [How generative AI and LLMs work](./conceptual/how-genai-and-llms-work.md).

docs/ai/quickstarts/build-chat-app.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,4 +145,4 @@ If you no longer need them, delete the Azure OpenAI resource and GPT-4 model dep
145145
## Next steps
146146
147147
- [Quickstart - Chat with a local AI model](chat-local-model.md)
148-
- [Generate images using AI with .NET](generate-images.md)
148+
- [Generate images from text using AI](text-to-image.md)

docs/ai/quickstarts/build-vector-search-app.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,4 +199,4 @@ If you no longer need them, delete the Azure OpenAI resource and model deploymen
199199
## Next steps
200200
201201
- [Quickstart - Chat with a local AI model](chat-local-model.md)
202-
- [Generate images using AI with .NET](generate-images.md)
202+
- [Generate images from text using AI](text-to-image.md)

docs/ai/quickstarts/generate-images.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
---
2-
title: Quickstart - Generate images using AI with .NET
3-
description: Create a simple app using to generate images using .NET and the OpenAI or Azure OpenAI models.
2+
title: Quickstart - Generate images using OpenAI.Images.ImageClient
3+
description: Create a simple app using to generate images using OpenAI.Images.ImageClient in .NET.
44
ms.date: 04/09/2025
55
ms.topic: quickstart
66
zone_pivot_groups: openai-library
7-
# CustomerIntent: As a .NET developer new to OpenAI, I want deploy and use sample code to interact to learn from the sample code to generate images.
87
---
98

10-
# Generate images using AI with .NET
9+
# Generate images using OpenAI.Images.ImageClient
1110

12-
In this quickstart, you learn how to create a .NET console app to generate images using an OpenAI or Azure OpenAI DALLe AI model, which are specifically designed to generate images based on text prompts.
11+
In this quickstart, you create a .NET console app that uses `OpenAI.Images.ImageClient` to generate images using an OpenAI or Azure OpenAI DALL-E AI model. These models generate images from text prompts.
1312

1413
:::zone target="docs" pivot="openai"
1514

@@ -101,7 +100,7 @@ Complete the following steps to create a .NET console app to connect to an AI mo
101100
:::code language="csharp" source="snippets/image-generation/azure-openai/program.cs" :::
102101
103102
> [!NOTE]
104-
> <xref:Azure.Identity.DefaultAzureCredential> searches for authentication credentials from your local tooling. If you aren't using the `azd` template to provision the Azure OpenAI resource, you'll need to assign the `Azure AI Developer` role to the account you used to sign-in to Visual Studio or the Azure CLI. For more information, see [Authenticate to Azure AI services with .NET](../azure-ai-services-authentication.md).
103+
> <xref:Azure.Identity.DefaultAzureCredential> searches for authentication credentials from your local tooling. If you aren't using the `azd` template to provision the Azure OpenAI resource, you'll need to assign the `Azure AI Developer` role to the account you used to sign in to Visual Studio or the Azure CLI. For more information, see [Authenticate to Azure AI services with .NET](../azure-ai-services-authentication.md).
105104
106105
:::zone-end
107106
2.2 MB
Loading
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// <SnippetConfigClient>
2+
using Azure;
3+
using Azure.AI.OpenAI;
4+
using Microsoft.Extensions.AI;
5+
using Microsoft.Extensions.Configuration;
6+
7+
IConfigurationRoot config = new ConfigurationBuilder()
8+
.AddUserSecrets<Program>()
9+
.Build();
10+
11+
string endpoint = config["AZURE_OPENAI_ENDPOINT"];
12+
string apiKey = config["AZURE_OPENAI_API_KEY"];
13+
string model = config["AZURE_OPENAI_GPT_NAME"];
14+
15+
// Create the Azure OpenAI client and convert to IImageGenerator.
16+
AzureOpenAIClient azureClient = new(
17+
new Uri(endpoint),
18+
new AzureKeyCredential(apiKey));
19+
20+
var imageClient = azureClient.GetImageClient(model);
21+
#pragma warning disable MEAI001 // Type is for evaluation purposes only.
22+
IImageGenerator generator = imageClient.AsIImageGenerator();
23+
// </SnippetConfigClient>
24+
25+
// <SnippetGenerateImage>
26+
// Generate an image from a text prompt
27+
var options = new ImageGenerationOptions
28+
{
29+
MediaType = "image/png"
30+
};
31+
string prompt = "A tennis court in a jungle";
32+
var response = await generator.GenerateImagesAsync(prompt, options);
33+
34+
// Save the image to a file.
35+
var dataContent = response.Contents.OfType<DataContent>().First();
36+
string fileName = SaveImage(dataContent, "jungle-tennis.png");
37+
Console.WriteLine($"Image saved to file: {fileName}");
38+
39+
static string SaveImage(DataContent content, string fileName)
40+
{
41+
string userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
42+
var path = Path.Combine(userDirectory, fileName);
43+
File.WriteAllBytes(path, content.Data.ToArray());
44+
return Path.GetFullPath(path);
45+
}
46+
// </SnippetGenerateImage>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net10.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="Azure.AI.OpenAI" Version="2.1.0" />
12+
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.10.1-preview.1.25521.4" />
13+
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.10" />
14+
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="9.0.10" />
15+
</ItemGroup>
16+
17+
</Project>
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
---
2+
title: Quickstart - Generate images from text using AI
3+
description: Learn how to use Microsoft.Extensions.AI to generate images from text prompts using AI models in a .NET application.
4+
ms.date: 10/21/2025
5+
ms.topic: quickstart
6+
ai-usage: ai-assisted
7+
---
8+
9+
# Generate images from text using AI
10+
11+
In this quickstart, you use the <xref:Microsoft.Extensions.AI> (MEAI) library to generate images from text prompts using an AI model. The MEAI text-to-image capabilities let you generate images from natural language prompts or existing images using a consistent and extensible API surface.
12+
13+
The <xref:Microsoft.Extensions.AI.IImageGenerator> interface provides a unified, extensible API for working with various image generation services, making it easy to integrate text-to-image capabilities into your .NET apps. The interface supports:
14+
15+
- Text-to-image generation.
16+
- Pipeline composition with middleware (logging, telemetry, caching).
17+
- Flexible configuration options.
18+
- Support for multiple AI providers.
19+
20+
> [!NOTE]
21+
> The `IImageGenerator` interface is currently marked as experimental with the `MEAI001` diagnostic ID. You might need to suppress this warning in your project file or code.
22+
23+
<!--Prereqs-->
24+
[!INCLUDE [azure-openai-prereqs](../quickstarts/includes/prerequisites-azure-openai.md)]
25+
26+
## Configure the AI service
27+
28+
To provision an Azure OpenAI service and model using the Azure portal, complete the steps in the [Create and deploy an Azure OpenAI Service resource](/azure/ai-services/openai/how-to/create-resource?pivots=web-portal) article. In the "Deploy a model" step, select the `gpt-image-1` model.
29+
30+
> [!NOTE]
31+
> `gpt-image-1` is a newer model that offers several improvements over DALL-E 3. It's available from OpenAI on a limited basis; apply for access with [this form](https://aka.ms/oai/gptimage1access).
32+
33+
## Create the application
34+
35+
Complete the following steps to create a .NET console application that generates images from text prompts.
36+
37+
1. Create a new console application:
38+
39+
```dotnetcli
40+
dotnet new console -o TextToImageAI
41+
```
42+
43+
1. Navigate to the `TextToImageAI` directory, and add the necessary packages to your app:
44+
45+
```dotnetcli
46+
dotnet add package Azure.AI.OpenAI
47+
dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
48+
dotnet add package Microsoft.Extensions.Configuration
49+
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
50+
```
51+
52+
1. Run the following commands to add [app secrets](/aspnet/core/security/app-secrets) for your Azure OpenAI endpoint, model name, and API key:
53+
54+
```bash
55+
dotnet user-secrets init
56+
dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
57+
dotnet user-secrets set AZURE_OPENAI_GPT_NAME gpt-image-1
58+
dotnet user-secrets set AZURE_OPENAI_API_KEY <your-azure-openai-api-key>
59+
```
60+
61+
1. Open the new app in your editor of choice (for example, Visual Studio).
62+
63+
## Implement basic image generation
64+
65+
1. Update the `Program.cs` file with the following code to get the configuration data and create the <xref:Azure.AI.OpenAI.AzureOpenAIClient>:
66+
67+
:::code language="csharp" source="snippets/text-to-image/azure-openai/Program.cs" id="ConfigClient":::
68+
69+
The preceding code:
70+
71+
- Loads configuration from user secrets.
72+
- Creates an `ImageClient` from the OpenAI SDK.
73+
- Converts the `ImageClient` to an `IImageGenerator` using the <xref:Microsoft.Extensions.AI.OpenAIClientExtensions.AsIImageGenerator(OpenAI.Images.ImageClient)> extension method.
74+
75+
1. Add the following code to implement basic text-to-image generation:
76+
77+
:::code language="csharp" source="snippets/text-to-image/azure-openai/Program.cs" id="GenerateImage":::
78+
79+
The preceding code:
80+
81+
- Sets the requested image file type by setting <xref:Microsoft.Extensions.AI.ImageGenerationOptions.MediaType?displayProperty=nameWithType>.
82+
- Generates an image using the <xref:Microsoft.Extensions.AI.ImageGeneratorExtensions.GenerateImagesAsync(Microsoft.Extensions.AI.IImageGenerator,System.String,Microsoft.Extensions.AI.ImageGenerationOptions,System.Threading.CancellationToken)> method with a text prompt.
83+
- Saves the generated image to a file in the local user directory.
84+
85+
1. Run the application, either through the IDE or using `dotnet run`.
86+
87+
The application generates an image and outputs the file path to the image. Open the file to view the generated image. The following image shows one example of a generated image.
88+
89+
:::image type="content" source="media/text-to-image/jungle-tennis.png" alt-text="AI-generated image of a tennis court in a jungle.":::
90+
91+
## Configure image generation options
92+
93+
You can customize image generation by providing other options such as size, response format, and number of images to generate. The <xref:Microsoft.Extensions.AI.ImageGenerationOptions> class allows you to specify:
94+
95+
- <xref:Microsoft.Extensions.AI.ImageGenerationOptions.AdditionalProperties>: Provider-specific options.
96+
- <xref:Microsoft.Extensions.AI.ImageGenerationOptions.Count>: The number of images to generate.
97+
- <xref:Microsoft.Extensions.AI.ImageGenerationOptions.ImageSize>: The dimensions of the generated image as a <xref:System.Drawing.Size?displayProperty=fullName>. For supported sizes, see the [OpenAI API reference](https://platform.openai.com/docs/api-reference/images/create).
98+
- <xref:Microsoft.Extensions.AI.ImageGenerationOptions.MediaType>: The media type (MIME type) of the generated image.
99+
- <xref:Microsoft.Extensions.AI.ImageGenerationOptions.ModelId>: The model ID.
100+
- <xref:Microsoft.Extensions.AI.ImageGenerationOptions.RawRepresentationFactory>: The callback that creates the raw representation of the image generation options from an underlying implementation.
101+
- <xref:Microsoft.Extensions.AI.ImageGenerationOptions.ResponseFormat>: Options are <xref:Microsoft.Extensions.AI.ImageGenerationResponseFormat.Uri>, <xref:Microsoft.Extensions.AI.ImageGenerationResponseFormat.Data>, and <xref:Microsoft.Extensions.AI.ImageGenerationResponseFormat.Hosted>.
102+
103+
## Best practices
104+
105+
When implementing text-to-image generation in your applications, consider these best practices:
106+
107+
- **Prompt engineering**: Write clear, detailed prompts that describe the desired image. Include specific details about style, composition, colors, and elements.
108+
- **Cost management**: Image generation can be expensive. Cache results when possible and implement rate limiting to control costs.
109+
- **Content safety**: Always review generated images for appropriate content, especially in production applications. Consider implementing content filtering and moderation.
110+
- **User experience**: Image generation can take several seconds. Provide progress indicators and handle timeouts gracefully.
111+
- **Legal considerations**: Be aware of licensing and usage rights for generated images. Review the terms of service for your AI provider.
112+
113+
## Clean up resources
114+
115+
When you no longer need the Azure OpenAI resource, delete it to avoid incurring charges:
116+
117+
1. In the [Azure Portal](https://portal.azure.com), navigate to your Azure OpenAI resource.
118+
1. Select the resource and then select **Delete**.
119+
120+
## Next steps
121+
122+
You've successfully generated some different images using the <xref:Microsoft.Extensions.AI.IImageGenerator> interface in <xref:Microsoft.Extensions.AI>. Next, you can explore some of the additional functionality, including:
123+
124+
- Refining the generated image iteratively.
125+
- Editing an existing image.
126+
- Personalizing an image, diagram, or theme.
127+
128+
## See also
129+
130+
- [Explore text-to-image capabilities in .NET (blog post)](https://devblogs.microsoft.com/dotnet/explore-text-to-image-dotnet/)
131+
- [Microsoft.Extensions.AI library overview](../microsoft-extensions-ai.md)
132+
- [Quickstart: Build an AI chat app with .NET](../quickstarts/build-chat-app.md)

docs/ai/toc.yml

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,21 @@ items:
33
href: index.yml
44
- name: Overview
55
href: overview.md
6-
- name: "Quickstart: Connect to and prompt an AI model"
7-
href: quickstarts/prompt-model.md
86
- name: AI tools and SDKs
97
items:
108
- name: Overview
119
href: dotnet-ai-ecosystem.md
1210
- name: Microsoft.Extensions.AI
13-
href: microsoft-extensions-ai.md
11+
href: microsoft-extensions-ai.md
1412
- name: Microsoft Agent Framework
1513
href: /agent-framework/overview/agent-framework-overview?toc=/dotnet/ai/toc.json&bc=/dotnet/ai/toc.json
1614
- name: C# SDK for MCP
1715
href: get-started-mcp.md
1816
- name: Quickstarts
17+
expanded: true
1918
items:
19+
- name: Connect to and prompt an AI model
20+
href: quickstarts/prompt-model.md
2021
- name: Build a chat app
2122
href: quickstarts/build-chat-app.md
2223
- name: Request structured output
@@ -25,18 +26,12 @@ items:
2526
href: quickstarts/build-vector-search-app.md
2627
- name: Execute a local .NET function
2728
href: quickstarts/use-function-calling.md
28-
- name: Generate images
29-
href: quickstarts/generate-images.md
3029
- name: Chat with a local AI model
3130
href: quickstarts/chat-local-model.md
3231
- name: Build a minimal AI assistant
3332
href: quickstarts/create-assistant.md
3433
- name: Get started using the AI app templates
3534
href: quickstarts/ai-templates.md
36-
- name: Build a minimal MCP server and publish to NuGet
37-
href: quickstarts/build-mcp-server.md
38-
- name: Build a minimal MCP client
39-
href: quickstarts/build-mcp-client.md
4035
- name: Concepts
4136
items:
4237
- name: How generative AI and LLMs work
@@ -67,6 +62,18 @@ items:
6762
href: tutorials/tutorial-ai-vector-search.md
6863
- name: Scale Azure OpenAI with Azure Container Apps
6964
href: get-started-app-chat-scaling-with-azure-container-apps.md
65+
- name: MCP client/server
66+
items:
67+
- name: Build a minimal MCP server and publish to NuGet
68+
href: quickstarts/build-mcp-server.md
69+
- name: Build a minimal MCP client
70+
href: quickstarts/build-mcp-client.md
71+
- name: Text to image
72+
items:
73+
- name: Generate images using MEAI
74+
href: quickstarts/text-to-image.md
75+
- name: Generate images using OpenAI.Images.ImageClient
76+
href: quickstarts/generate-images.md
7077
- name: Security and content safety
7178
items:
7279
- name: Authentication for Azure-hosted apps and services

0 commit comments

Comments
 (0)