How To Generate Images Using OpenAI
March 11, 2024
Background Information
Lately, there's been a surge of TikTok videos showcasing AI-generated images created using ChatGPT, which sparked my curiosity. However, subscribing to ChatGPT Plus at $20 a month seemed pricey. Therefore, using my existing knowledge with OpenAI's API, I explored a more affordable way to generate images. In this post, I'll guide you through the process of generating images using OpenAI's API.
Prerequisites
Before you start, ensure you have the following:
- An OpenAI account.
- An OpenAI API key.
- Sufficient account funds.
- Node.js installed.
Create a Project Folder and JavaScript File
First, create a new folder for your project and add a file named generate.js. This file will contain the code to generate images. Change your current directory to the newly created folder.
Install Required NPM Packages
npm i openai
Generate and Save the Image Locally
Create the following code in the generate.js file to generate and save an image:
import OpenAI from "openai";
import { writeFile } from "fs";
const openai = new OpenAI({
apiKey: "YOUR_API_KEY",
});
const response = await openai.images.generate({
model: "dall-e-3",
prompt:
"A seven foot blue alien driving a red porsche.",
n: 1,
size: "1024x1024",
response_format: "b64_json", // use 'url' if you prefer to have a link to your image.
});
const imageBase64Data = response.data[0]["b64_json"];
const imageBufferData = Buffer.from(imageBase64Data, "base64");
// Specify the path and filename for the output image
const filePath = "./outputImage.png";
// Write the buffer to a file
writeFile(filePath, imageBufferData, (err) => {
if (err) {
console.error("Error saving the image file:", err);
} else {
// Shows the formatted prompt and the base64 code.
console.log(response.data);
}
});
Generate an Image and Get URL
You can also generate an image and obtain its URL:
import OpenAI from "openai";
import { writeFile } from "fs";
const openai = new OpenAI({
apiKey: "YOUR_API_KEY",
});
const response = await openai.images.generate({
model: "dall-e-3",
prompt:
"A seven foot blue alien driving a red porsche.",
n: 1,
size: "1024x1024",
response_format: "url", // use 'url' if you prefer to have a link to your image.
});
console.log(response.data[0]) // Get response plus the URL to the image
Execute the Code
Run the script using the following command:
node .\generate.js