Using DALL-E in an ASP.NET Core application involves integrating the OpenAI API into your code. We can generate multiple images based on the given text using DALL-E generate image API endpoint. First, you must develop an OpenAI API key to authorize API use. In this article, I will explain how you can use DALL-E API in the ASP.NET Core MVC application to generate images based on the text.
Agenda for the Article,
What is OpenAI?
What is DALL-E?
How to get OpenAI API Key
Generating Image In ASP.NET Core MVC
What is OpenAI?
OpenAI is an artificial intelligence research lab that works to develop and grow AI in different fields like medicine, education, sports, information technology, etc. It was founded in 2015. OpenAI conducts research in various areas of AI, including machine learning, natural language processing, robotics, and computer vision. The organization has developed several groundbreaking AI models, including GPT-3, DALL-E, and CLIP. In this article, I will explain the use of the DALL-E. I have also written an article on GPT-3. To know more, please refer to this article.
What is DALL-E?
DALL-E is an artificial intelligence (AI) program developed by OpenAI that generates images from textual descriptions using a transformer-based language model. DALL-E is named after the famous artist Salvador Dali. The program can create highly detailed and complex images of objects, animals, and scenes that do not exist in the real world but also in the real world. It works by learning from a dataset of images and their associated textual descriptions, allowing it to generate fictional and realistic images based on the given textual input. DALL-E is a significant breakthrough in AI image generation and has the potential to revolutionize various industries, including advertising, gaming, and e-commerce.
Generating OpenAI API Key
You need to authorize the API endpoint by passing the API key. To generate an OpenAI API key, follow these steps:
Signup for an OpenAI account. Go to the OpenAI website and create a new account.
Confirm your email address.
Now, Log in to your account and navigate to the 'View API keys' section as given below.
Now, click on 'Create new secret key' as given below.
Store your API key in a secure location, as it will be required to access the OpenAI APIs. You can copy the key and save it for future use. OpenAI has usage and resource limitations for its API, so be sure to check its documentation here for details on usage and pricing.
Generating Image In ASP.NET Core MVC
To generate images in the ASP.NET Core MVC application using DALL-E, you need to follow the below-given steps:
First, create an ASP.NET Core MVC project. To know more about creating a project, please refer here.
Add your API key in the appsettings.json file as given below
//demo key
"OpenAI_API_KEY": "sk-cF8Dv3n2YtUXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Add the below-given code for the UI in your Index.cshtml file inside Views>Home>Index.cshtml
<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>
<option>512x512</option>
</select>
<!--Images Required-->
<input type="number" value="1" placeholder="Images Required" id="quantity" />
<!--Generate button-->
<button id="generate">
Generate
</button>
<br />
<!--Display image here-->
<div id="Imagedisplay" class="col-md-14 row">
</div>
In the above-given code, you have added a UI for the home page to enter some basic details required for the image, like the information about the image, the number of images required, and the size of the image.
Now you will add a model class ImageInfo.cs inside the Models folder as given below.
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;
}
}
// response handling
public class ResponseModel {
public long created {
get;
set;
}
public List < ImageUrls > ? data {
get;
set;
}
}
In the above-given code, You have added ResponseModel class for handling the response and RequiredImage class for the input data about the required image.
Now you will add a controller method inside HomeController.cs as given below.
[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);
}
You have added a post-call with the DALL-E API key in the above given code. You have to pass the API key shown above.
The final step is to display the image on the UI using javascript. So you have to add the below-given code inside wwwroot>js>site.js.
$(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('<div class="col-md-5" style="padding-top:12px">' + '<img class="p-12" src = "' + this.url + '"/>' + '</div>');
});
});
});
});
Output
Conclusion
OpenAI provides us with lots and lots of use for artificial intelligence. AI has become a part of our daily life nowadays. ChatGPT and DALL-E are all advanced and great examples of AI. To generate an image, you need two things. First, the OpenAI APOI key and second DALL-E API endpoint. Pass the API key in the header and freely use that endpoint.
Thank You, and Stay Tuned for More.