Edit

Share via


Generate images using AI with .NET

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.

Prerequisites

Prerequisites

Note

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.

Create the app

Complete the following steps to create a .NET console app to connect to an AI model.

  1. In an empty directory on your computer, use the dotnet new command to create a new console app:

    dotnet new console -o ImagesAI
    
  2. Change directory into the app folder:

    cd ImagesAI
    
  3. Install the required packages:

    dotnet add package Azure.AI.OpenAI
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
    dotnet add package OpenAI
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
  4. Open the app in Visual Studio Code or your editor of choice.

    code .
    

Create the AI service

  1. To provision an Azure OpenAI service and model, complete the steps in the Create and deploy an Azure OpenAI Service resource article.

  2. From a terminal or command prompt, navigate to the root of your project directory.

  3. Run the following commands to configure your Azure OpenAI endpoint and model name for the sample app:

    dotnet user-secrets init
    dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
    dotnet user-secrets set AZURE_OPENAI_GPT_NAME <your-Azure-OpenAI-model-name>
    

Configure the app

  1. Navigate to the root of your .NET project from a terminal or command prompt.

  2. Run the following commands to configure your OpenAI API key as a secret for the sample app:

    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

  1. In the Program.cs file, add the following code to connect and authenticate to the AI model.

    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}");
    

    Note

    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.

    // 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 OpenAI.Images.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.
  2. Run the app:

    dotnet run
    

    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

If you no longer need them, delete the Azure OpenAI resource and GPT-4 model deployment.

  1. In the Azure Portal, navigate to the Azure OpenAI resource.
  2. Select the Azure OpenAI resource, and then select Delete.

Next steps