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.
You can also use Semantic Kernel to accomplish the tasks in this article. Semantic Kernel is a lightweight, open-source SDK that lets you build AI agents and integrate the latest AI models into your .NET apps.
Clone the sample repository
You can create your own app using the steps in the sections ahead, or you can clone the GitHub repository that contains the completed sample apps for all of the quickstarts. If you plan to use Azure OpenAI, the sample repo is also structured as an Azure Developer CLI template that can provision an Azure OpenAI resource for you.
The sample GitHub repository is structured as an Azure Developer CLI (azd) template, which azd can use to provision the Azure OpenAI service and model for you.
From a terminal or command prompt, navigate to the src\quickstarts\azure-openai directory of the sample repo.
Run the azd up command to provision the Azure OpenAI resources. It might take several minutes to create the Azure OpenAI service and deploy the model.
Azure Developer CLI
azd up
azd also configures the required user secrets for the sample app, such as the Azure OpenAI endpoint and model name.
From a terminal or command prompt, navigate to the root of your project directory.
Run the following commands to configure your Azure OpenAI endpoint and model name for the sample app:
Bash
dotnet user-secrets init
dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-openai-key>
dotnet user-secrets set AZURE_OPENAI_GPT_NAME <your-azure-openai-model-name>
Configure the app
Navigate to the root of your .NET project from a terminal or command prompt.
Run the following commands to configure your OpenAI API key as a secret for the sample app:
Bash
dotnet user-secrets init
dotnet user-secrets set OpenAIKey <your-openai-key>
dotnet user-secrets set ModelName <your-openai-model-name>
Add the app code
In the Program.cs file, add the following code to connect and authenticate to the AI model.
C#
using Microsoft.Extensions.Configuration;
using OpenAI.Images;
using System.ClientModel;
using Azure.AI.OpenAI;
using Azure.Identity;
// Retrieve the local secrets saved during the Azure deployment. If you skipped the deployment// because you already have an Azure OpenAI available, edit the following lines to use your information,// e.g. string openAIEndpoint = "https://cog-demo123.openai.azure.com/";var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string endpoint = config["AZURE_OPENAI_ENDPOINT"];
string deployment = config["AZURE_OPENAI_DALLE_NAME"];
// Create the Azure OpenAI ImageClient
ImageClient client =
new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
.GetImageClient(deployment);
// Generate the image
GeneratedImage generatedImage = await client.GenerateImageAsync("""
A postal card with an happy hiker waving and a beautiful mountain in the background.
There is a trail visible in the foreground.
The postal card has text in red saying: 'You are invited for a hike!'
""", new ImageGenerationOptions { Size = GeneratedImageSize.W1024xH1024 });
Console.WriteLine($"The generated image is ready at:\n{generatedImage.ImageUri}");
Not
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.
C#
// Licensed to the .NET Foundation under one or more agreements.// The .NET Foundation licenses this file to you under the MIT license.// See the LICENSE file in the project root for more information.using Microsoft.Extensions.Configuration;
using OpenAI.Images;
// Retrieve the local secrets that were set from the command line, using:// dotnet user-secrets init// dotnet user-secrets set OpenAIKey <your-openai-key>var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string key = config["OpenAIKey"];
string modelName = config["ModelName"];
// Create the OpenAI ImageClient
ImageClient client = new(modelName, key);
// Generate the image
GeneratedImage generatedImage = await client.GenerateImageAsync("""
A postal card with a happy hiker waving and a beautiful mountain in the background.
There is a trail visible in the foreground.
The postal card has text in red saying: 'You are invited for a hike!'
""",
new ImageGenerationOptions
{
Size = GeneratedImageSize.W1024xH1024
});
Console.WriteLine($"The generated image is ready at:\n{generatedImage.ImageUri}");
The preceding code:
Reads essential configuration values from the project user secrets to connect to the AI model
Creates an ImageClient to connect to the AI model
Sends a prompt to the model that describes the desired image
Prints the URL of the generated image to the console output
Use the dotnet run command to run the app:
.NET CLI
dotnetrun
Navigate to the image URL in the console output to view the generated image. Customize the text content of the prompt to create new images or modify the original.
Clean up resources
When you no longer need the sample application or resources, remove the corresponding deployment and all resources.
Bu içeriğin kaynağı GitHub'da bulunabilir; burada ayrıca sorunları ve çekme isteklerini oluşturup gözden geçirebilirsiniz. Daha fazla bilgi için katkıda bulunan kılavuzumuzu inceleyin.
.NET geri bildirimi
.NET, açık kaynak bir projedir. Geri bildirim sağlamak için bir bağlantı seçin:
Diğer geliştiriciler ve uzmanlarla gerçek dünyadaki kullanım örneklerini temel alan ölçeklenebilir yapay zeka çözümleri oluşturmak için toplantı serisine katılın.
Yapay zeka destekli görüntü oluşturucuları keşfedin. Microsoft Image Creator gibi görüntü oluşturma araçları hakkında bilgi edinin. İş yeri ve eğitim ayarlarındaki potansiyel uygulamalarını anlayın ve en iyi sonuçlar için en iyi yöntemleri keşfedin. Yapay zeka destekli görüntü oluşturucularla becerilerinizi geliştirin ve yaratıcı sürecinizi dönüştürün.