Generating Images in ASP.NET Core MVC using OpenAI

Harsh Bakshi
4 min readJul 12, 2023

--

Introduction

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
"OpenAI_API_KEY": "API_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:

Image Generator

256x256    512x512




Generate

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
get;
set;


public class RequiredImage
public string ? prompt
get;
set;

public short ? n
get;
set;

public string ? size
get;
set;


public class ImageUrls
public string ? url
get;
set;


// Handling the response
public class ResponseModel
public long created
get;
set;

public List < ImageUrls > ? data
get;
set;

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:
[HttpPost]
public async Task < IActionResult > GenerateImage([FromBody] RequiredImage obj)
string imglink = string.Empty;
var response = new ResponseModel();
using(var client = new HttpClient())
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", APIKEY);
var Message = await client.PostAsync("https://api.openai.com/v1/images/generations", new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json"));
if (Message.IsSuccessStatusCode)
var content = await Message.Content.ReadAsStringAsync();
response = JsonConvert.DeserializeObject < ResponseModel > (content);
imglink = resp.data[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();
$.ajax(
url: '/Home/GenerateImage',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(info)
).done(function(data)
$.each(data.data, function()
$('#Imagedisplay').append('
' + '' + '');
);
);
);
);

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.

Conclusion

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 https://skrots.com. Feel free to explore our wide range of services at https://skrots.com/services. Thank you for reading, and stay tuned for more exciting articles!

Popular Articles from My Account

Thanks, Harsh
Founder | CEO — Skrots

Learn more about our blog at Blog at Skrots. Checkout our list of services on Skrots. Give a look at our website design at Skrots . Checkout our LinkedIn Page at LinkedIn.com. Check out our original post at https://blog.skrots.com/generate-images-in-asp-net-core-mvc-using-openai/?feed_id=222&_unique_id=64aed059cc9a8.

--

--

No responses yet