Artificial Intelligence

Generating Images in ASP.NET Core MVC using OpenAI


Imagine being able to generate multiple images just by providing a text description. Thanks to DALL-E, an artificial intelligence (AI) program developed by OpenAI, this is now possible. In this article, I will explain how you can integrate DALL-E’s generate image API endpoint into an ASP.NET Core MVC application to generate images based on text input.

Here’s what we’ll cover in this article:

  1. What is OpenAI?
  2. What is DALL-E?
  3. How to obtain an OpenAI API Key
  4. Generating Images in ASP.NET Core MVC

What is OpenAI?

OpenAI is an AI research lab established in 2015. Their mission is to develop and promote artificial intelligence in various domains such as medicine, education, sports, and information technology. OpenAI conducts research in areas like machine learning, natural language processing, robotics, and computer vision. The organization has created groundbreaking AI models such as GPT-3, DALL-E, and CLIP, which we will focus on in this article.

What is DALL-E?

DALL-E is an AI program developed by OpenAI that generates images based on textual descriptions. This program is named after the renowned artist Salvador Dali and utilizes a transformer-based language model. By learning from a dataset of images and corresponding textual descriptions, DALL-E can create detailed and complex images that don’t exist in the real world. These generated images have immense potential in industries like advertising, gaming, and e-commerce.

Obtaining an OpenAI API Key

To use the OpenAI API and integrate it into your ASP.NET Core MVC application, you’ll need an API key. Here’s how you can obtain one:

  1. Create an account on the OpenAI website.
  2. Confirm your email address.
  3. Log in to your account and navigate to the “View API keys” section.
  4. Click on “Create new secret key” to generate an API key.

Make sure to store your API key securely, as you’ll need it to access the OpenAI APIs. OpenAI has usage and resource limitations, so be sure to check their documentation for further details on usage and pricing.

Generating Images in ASP.NET Core MVC

Now, let’s dive into the process of generating images in an ASP.NET Core MVC application using DALL-E. Follow these steps:

  1. Create an ASP.NET Core MVC project. If you’re unsure how to do this, you can refer to this helpful guide: [link to creating an ASP.NET Core MVC project]
  2. Add your API key to the “appsettings.json” file in the following format:
// Replace API_KEY with your actual key

In the above step, replace “API_KEY” with your actual OpenAI API key.

  1. Add the following code to the “Index.cshtml” file in the “Views > Home” folder:
<h1 class="display-4">Image Generator</h1>
<!--Image info-->
<input type="text" class="form-control" id="txt" style="width:400px;" placeholder="Image Description" />
<br />
<!--Image Size-->
<select id="size">
    <option selected>256x256</option>
<!--Images Required-->
<input type="number" value="1" placeholder="Images Required" id="quantity" />
<!--Generate button-->
<button id="generate">
<br />
<!--Display image here-->
<div id="Imagedisplay" class="col-md-14 row">

In the above code, we have added a user interface (UI) for the home page. Users can enter details such as the image description, image size, and the number of images required.

  1. Create a model class named “ImageInfo.cs” in the “Models” folder. Add the following code to the file:
public class ImageInfo {
    public string ? ImageText {
public class RequiredImage {
    public string ? prompt {
    public short ? n {
    public string ? size {
public class ImageUrls {
    public string ? url {
// Handling the response
public class ResponseModel {
    public long created {
    public List < ImageUrls > ? data {

In the “ImageInfo” class, we have defined the image text property. The “RequiredImage” class represents the input data required for the image generation. The “ImageUrls” class defines the URL property of the generated images. Lastly, the “ResponseModel” class handles the response from the API.

  1. Add the following code to the “HomeController.cs” file:
public async Task < IActionResult > GenerateImage([FromBody] RequiredImage obj) {
    string imglink = string.Empty;
    var response = new ResponseModel();
    using(var client = new HttpClient()) {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", APIKEY);
        var Message = await client.PostAsync("", new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"));
        if (Message.IsSuccessStatusCode) {
            var content = await Message.Content.ReadAsStringAsync();
            response = JsonConvert.DeserializeObject < ResponseModel > (content);
            imglink =[0].url.ToString();
    return Json(response);

In the “GenerateImage” method, we make a POST request to the DALL-E API endpoint using the provided API key. The API response is then deserialized into the “ResponseModel” class, and the URL of the generated image is extracted.

  1. Install the jQuery library and add the following code to the “site.js” file in the “wwwroot > js” folder:
$(document).ready(() => {
    $('#generate').click(function() {
        var info = {};
        info.n = parseInt($('#quantity').val());
        info.prompt = $('#txt').val();
        info.size = $('#size').find(":selected").val();
            url: '/Home/GenerateImage',
            method: 'post',
            contentType: 'application/json',
            data: JSON.stringify(info)
        }).done(function(data) {
            $.each(, function() {
                $('#Imagedisplay').append('<div class="col-md-5" style="padding-top:12px">' + '<img class="p-12" src = "' + this.url + '"/>' + '</div>');

This code makes an AJAX request to the “GenerateImage” action method in the “HomeController” class. It passes the input data as JSON and appends the generated images to the “Imagedisplay” section of the web page.

That’s it! You have successfully integrated DALL-E image generation into your ASP.NET Core MVC application. Now, you can generate images based on textual descriptions with ease.


OpenAI provides us with incredible opportunities to leverage artificial intelligence in various applications. AI has become an integral part of our daily lives, and with tools like DALL-E, we can unlock even more potential. At Skrots, we offer similar services to OpenAI, allowing you to harness the power of AI and automation in your projects. To learn more about Skrots and the services we provide, visit Feel free to explore our wide range of services at Thank you for reading, and stay tuned for more exciting articles!

Popular Articles from My Account

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button