Topview Logo
  • Create viral videos with
    GPT-4o + Ads library
    Use GPT-4o to edit video empowered by Youtube & Tiktok & Facebook ads library. Turns your links or media assets into viral videos in one click.
    Try it free
    gpt video

    Minimal API .NET 8 and DALL-E to Generate Images | Open AI dall-e-3 #openai

    blog thumbnail

    Minimal API .NET 8 and DALL-E to Generate Images | Open AI dall-e-3 #openai

    In this article, we'll walk through the process of creating a minimal API using .NET 8 that leverages OpenAI's DALL-E to generate images based on user input. This tutorial assumes you have a basic understanding of .NET and API development. Let's get started!

    Step 1: Creating a New .NET Project

    First, we need to create a new .NET project:

    dotnet new webapi -o ImageGenerationAPI
    cd ImageGenerationAPI
    

    Once created, clean up the Program.cs by removing unnecessary lines and dependencies:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using OpenAI.Generator;
    
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    
    app.MapPost("/generate-image", (ImageRequest request, ImageGeneratorClient client) => (
        var options = new GenerateOptions
        {
            Quality = ImageQuality.High,
            Size = ImageSize.Medium,
            Style = ImageStyle.Natural,
            ResponseFormat = ResponseFormat.Uri
        );
        var response = client.GenerateImageAsync(request.Input, options).Result;
        return Results.Ok(response);
    });
    
    app.Run();
    
    class ImageRequest
    (
        public string Input { get; set; )
    }
    

    Step 2: Setting Up OpenAI API Key

    Next, generate and configure an API key from OpenAI:

    1. Visit the OpenAI platform portal.
    2. Generate an API key.
    3. Copy and securely store the key (you can save it in an environment variable or configuration file):
    var apiKey = "your-openai-api-key";
    var client = new ImageGeneratorClient(apiKey);
    

    Step 3: Adding Necessary Dependencies

    Add the required NuGet package to the project:

    dotnet add package OpenAI.Generator --version (latest-version)
    dotnet restore
    

    Replace (latest-version) with the latest version number available.

    Step 4: Implementing the Image Generation Logic

    Next, we set up the client and image generation options:

    1. Create an instance of ImageGeneratorClient using the API key.
    2. Define image generation options like quality, size, style, and response format.

    Here's the complete code snippet for reference:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using OpenAI.Generator;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSingleton(new ImageGeneratorClient("your-openai-api-key"));
    
    var app = builder.Build();
    
    app.MapPost("/generate-image", async (ImageRequest request, ImageGeneratorClient client) => (
        var options = new GenerateOptions
        {
            Quality = ImageQuality.High,
            Size = ImageSize.Medium,
            Style = ImageStyle.Natural,
            ResponseFormat = ResponseFormat.Uri
        );
        try 
        (
            var response = await client.GenerateImageAsync(request.Input, options);
            return Results.Ok(response);
        )
        catch (Exception ex)
        (
            return Results.Problem(ex.Message);
        )
    });
    
    app.Run();
    
    class ImageRequest
    (
        public string Input { get; set; )
    }
    

    Step 5: Running and Testing the API

    Run the application:

    dotnet run
    

    Open your browser and navigate to /swagger to access the API documentation. Test the image generation endpoint by providing a description. For example, "cat inside a car with a laptop".

    Example Output

    The API will return an image URL. For instance, a generated image URL might point to an image of a cat inside a car with a laptop.

    Conclusion

    Integrating OpenAI's DALL-E with .NET 8 to generate images is straightforward. By following these steps, you can quickly set up a minimal API that generates images based on user input.

    Don't forget to subscribe to my channel for more tutorials!

    Keywords

    • .NET 8
    • Minimal API
    • OpenAI
    • DALL-E
    • Image Generation
    • ASP.NET Core
    • API Key
    • NuGet Package

    FAQ

    Q: How do I start a new .NET 8 project for this tutorial? A: Use dotnet new webapi -o ImageGenerationAPI to create a new web API project and then navigate into the directory with cd ImageGenerationAPI.

    Q: Where can I get an API key for OpenAI? A: You can generate an API key from the OpenAI platform portal.

    Q: What version of the OpenAI.Generator package should I use? A: Always use the latest version. You can find the latest version on the NuGet package website.

    Q: How do I test the API endpoint? A: Run the application with dotnet run and navigate to /swagger in your browser to test the API endpoint.

    Q: What should I do if the image URL does not show the expected content? A: Ensure your input text is clear and descriptive. You might need to experiment with different descriptions to get better results.

    One more thing

    In addition to the incredible tools mentioned above, for those looking to elevate their video creation process even further, Topview.ai stands out as a revolutionary online AI video editor.

    TopView.ai provides two powerful tools to help you make ads video in one click.

    Materials to Video: you can upload your raw footage or pictures, TopView.ai will edit video based on media you uploaded for you.

    Link to Video: you can paste an E-Commerce product link, TopView.ai will generate a video for you.

    You may also like