One of the most popular image generation tools is DALL-E 2, which generates images based on user prompts in natural language. If you are a developer who wants to integrate the DALL-E 2 API into your apps or services, you can use deep learning and massive datasets to generate state-of-the-art images from text descriptions.
The latest release of the DALL-E image generator creates original images from text prompts. This article will share how to use the DALL-E 2 API to generate images. You can generate an image with a range of sizes, including 256×256, 512×512, or 1024×1024 pixels, and can request from 1 to 10 images at a time using the parameter, which is not possible with OpenAI DALL-E on the web.
Get the OpenAI API Key
To establish a connection between the OpenAI server and your series to make requests, you need an OpenAI account. To obtain your OpenAI API key, open the OpenAI platform and click on the profile icon in the screen’s upper-right corner. From the context menu, select “View API keys.”
After that, create a secret key for yourself and save it somewhere accessible.
Set up Development environments.
First, you need to set up the environment by installing relevant libraries like Python, or react and setting up your programming environment.
- Open Microsoft Visual Studio.
- Within your React app, create a.env file where your API key will be stored.
- Add the API key: VITE_Open_AI_Key = “Your API Key.”
Note:.env may differ in Create React App (CRA) and Vite React App. In our case, it is Vite.
Make a Function to call the OpenAI API.
Now, you must make an HTTP request to the DALL-E 2 API endpoint and include the API key.
- Import a few things into our React app’s App.js or App.jsx file, including the parameters of the OpenAI API from the OpenAI SDK.
- Now execute “npm install openai.”
- After that, execute the configuration import: “import { Configuration, OpenAIApi } from ‘openai’.”
- We can now start creating the configuration, which takes the API key from the env file.
- With the following command, we can create a new instance for the OpenAI API: “const openai = new OpenAIApi(configuration);”
To use the API from a Python script, use the openAI library and create_image functions.
import openai
openai.api_key = os.environ["OPENAI_API_KEY"]
prompt = "an image of an underwater modern city with fishes."
response = openai.Image.create(prompt=prompt, model="image-alpha-001")
Format the Input
Now you do need to specific formatting for input data, for which you need to format your input into correct manner for Api to understand your call.
import { Configuration, OpenAIApi } from "openai";
import { useState } from "react";
import "./App.css";
function App() {
const [prompt, setPrompt] = useState("");
const configuration = new Configuration({
apiKey: import.meta.env.VITE_Open_AI_Key,
});
const openai = new OpenAIApi(configuration);
return (
<div className="app-main">
<>
<h2>Generate an Image using Open AI API</h2>
<textarea
className="app-input"
placeholder="Search Bears with Paint Brushes the Starry Night, painted by Vincent Van Gogh.."
onChange={(e) => setPrompt(e.target.value)}
rows="10"
cols="40"
/>
<button onClick={generateImage}>Generate an Image</button>
</>
</div>
);
}
export default App;
Send the Request
Once you format the input you do need to create a https request to DALL-E 2 API.
const generateImage = async () => {
await openai.createImage({
prompt: prompt,
n: 1,
size: "512x512",
});
};
Handle the response
If everything work as it expected, it will not return a response that iOS image generated by DALL-E 2 which you should handle appropriately in your code. With the openai.createimage returns some response which stores variable.
const generateImage = async () => {
const res = await openai.createImage({
prompt: prompt,
n: 1,
size: "512x512",
});
console.log(res.data.data[0].url);
};
Use or store the result
That’s it, once you finish initial setup you can now use it based on your preference like the interafxe or download to view the image later. Also, we can use to store this image link so that we can view the image in the UI itself.
All the images will be appeared under results stae, which also render the image in the UI but the initial results will be empty.
const [result, setResult] = useState("");
const generateImage = async () => {
const res = await openai.createImage({
prompt: prompt,
n: 1,
size: "512x512",
});
setResult(res.data.data[0].url);
};
All the images will be appeared under results stae, which also render the image in the UI but the initial results will be empty.
{result.length > 0 ? (
<img className="result-image" src={result} alt="result" />
) : (
<></>
)}
And the output will be look like this,
.result-image {
margin-top: 20px;
width: 350px;
}
Save the image data to a file, for which you can API that you can use on Python.
import base64
with open("image.jpg", "wb") as f:
f.write(base64.b64decode(response["data"]))
To create a variation of an Image, Variations parameter to the create_iamge function.
import openai
openai.api_key = os.environ["OPENAI_API_KEY"]
prompt = "an image of an underwater modern city with fishes."
variations = ["an image of an underwater modern city with fishes in the forest.", "an image of an underwater modern city with fishes in the middle of the night."]
response = openai.Image.create(prompt=prompt, model="image-alpha-001", variations=variations)
How to Use DALL-E Online
You can use DALL-E 2 on the web as well. To do so, head to the DALL-E website and log in with your OpenAI account. Then, there will be a text box where you must type your prompt and hit “generate.” Wait a few seconds for DALL-E to generate your image, and then choose from four images. You can download, save to your collection, share to a public feed to further edit, or create more variants by clicking “more variations.”
However, it only comes with an unlimited number of image generations. It has 15 free credits to use each month. It would be best if you bought additional credits, which cost $15 for 115 credits. As for Playgrounds, head over to the OpenAI Platform and choose “Image Generation” from the OpenAI Platform. To learn more about image generation with DALL-E, Check the docs for the same.
To get more insights on using the DALL-E API, check out the documents to get the most out of the developer platforms. Before using the API, check out the OpenAI Playgrounds. You can try the DALL-E API to check its potential before deploying it on your local machine. So, this is how you can create your own React Application with DALL-E API to generate images using AI.