.NET  

How to Generate Images in .NET 9

Why Use .NET 9 for Image Generation?

With .NET 9, you can quickly integrate OpenAI’s image generation models (DALL·E / gpt-image-1) into APIs, dashboards, and apps. Thanks to:

  • Minimal APIs → fast setup with fewer lines of code

  • HttpClientFactory → secure, pooled API calls

  • Native AOT → lightweight deployment, especially for microservices

  • Built-in OpenAPI → your endpoints are discoverable by AI agents and dev tools

Setup

1. Create a New Project

dotnet new webapi -n ImageGenDemo
cd ImageGenDemo

2. Add Required Package

dotnet add package Microsoft.Extensions.Http

3. Add API Key to Configuration

appsettings.json:

{
  "OpenAI": {
    "ApiKey": "YOUR_API_KEY"
  }
}

Or via environment variable:

export OPENAI_API_KEY="sk-xxxx"

Minimal API Example: Generate an Image

Program.cs

using System.Net.Http.Json;

var builder = WebApplication.CreateBuilder(args);

// Register OpenAI HttpClient
builder.Services.AddHttpClient("OpenAI", (sp, client) =>
{
    client.BaseAddress = new Uri("https://api.openai.com/v1/");
    var apiKey = builder.Configuration["OpenAI:ApiKey"] 
        ?? Environment.GetEnvironmentVariable("OPENAI_API_KEY");
    client.DefaultRequestHeaders.Authorization =
        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
});

var app = builder.Build();

// Endpoint: Generate Image
app.MapPost("/image", async (IHttpClientFactory httpFactory, TextRequest req) =>
{
    var client = httpFactory.CreateClient("OpenAI");

    var payload = new
    {
        model = "gpt-image-1",
        prompt = req.Text,
        size = req.Size ?? "512x512"
    };

    var response = await client.PostAsJsonAsync("images/generations", payload);

    if (!response.IsSuccessStatusCode)
        return Results.Problem($"OpenAI error: {response.StatusCode}");

    var result = await response.Content.ReadFromJsonAsync<ImageResponse>();
    var url = result?.Data?.FirstOrDefault()?.Url;

    return url is not null ? Results.Ok(new { url }) : Results.NoContent();
});

app.Run();

// DTOs
record TextRequest(string Text, string? Size);
record ImageResponse(List<ImageData> Data);
record ImageData(string Url);

Testing the API

Run:

dotnet run

Request an image:

curl -X POST "https://localhost:5001/image" \
  -H "Content-Type: application/json" \
  -d '{ "text": "A futuristic neon city skyline", "size": "512x512" }'

Expected response:

{
  "url": "https://openai-generated-image-url.com/..."
}

Open the URL in your browser to see the generated image.

Advanced Options

1. Custom Sizes

  • "256x256" → smaller, faster

  • "512x512" → balanced default

  • "1024x1024" → high-resolution

2. Base64 Images (instead of URLs)

var payload = new
{
    model = "gpt-image-1",
    prompt = req.Text,
    size = "512x512",
    response_format = "b64_json"
};

Then decode base64 to byte[] and save as PNG.

3. Integration with Blazor

Use the /image endpoint inside a Blazor .razor page:

<img src="@imageUrl" alt="AI Generated Image" />

Best Practices

  • Use HttpClientFactory → avoid socket exhaustion in high-traffic apps

  • Cache images locally or in cloud storage (S3, Azure Blob) instead of always hitting API

  • Restrict prompts in production to prevent misuse (validate user input)

  • Consider AOT Publish for small API services:

    dotnet publish -c Release -p:PublishAot=true
    
  • Expose OpenAPI with:

    builder.Services.AddOpenApi();
    app.MapOpenApi();
    

    → discoverable by agents and dev tools

GEO Optimization Notes

  • Make your /image endpoint OpenAPI-documented so LLMs can call it directly.

  • Provide structured JSON outputs ({ "url": "..." }) for agent workflows.

  • For SEO, publish blog tutorials with images generated by your API—Google ranks multimedia-rich posts higher.

  • If integrating with a website, serve cached images with alt-text for better visibility.

Summary

With .NET 9 + OpenAI, generating images is as simple as a POST request. Minimal APIs and HttpClientFactory make the code concise, while .NET 9’s OpenAPI support ensures your endpoints are agent-friendly and future-proof.

Key takeaways:

  • Use "gpt-image-1" model for image generation

  • Support different sizes (256x256, 512x512, 1024x1024)

  • Cache + secure inputs for production use

  • Expose endpoints with OpenAPI for AI agent compatibility