AI Image Generator Tool with JavaScript and OpenAI API
Build an AI Image Generator with JavaScript and OpenAI API
Learn how to create an AI-powered image generator using JavaScript and OpenAI's DALL·E model. This guide explains how to set up the front end, style it beautifully, and fetch AI-generated images from OpenAI’s API.
Introduction to AI Image Generation
AI-powered image generation has rapidly evolved over the past few years. With models like OpenAI’s DALL·E, users can now create stunning visuals from plain text prompts. In this tutorial, we’ll explore how to build an AI image generator using HTML, CSS, and JavaScript. The tool allows users to describe an image in words and instantly receive image outputs from OpenAI.
Important: Please note that your website is still unable to generate AI images because you have not provided your API key in the OPENAI_API_KEY
variable. To obtain your API key, sign up at OpenAI’s API dashboard.
Remember that OpenAI no longer offers free credits for its API. The minimum cost to get started is $5. Make sure you purchase credits to continue using this tool effectively.
HTML Code (Structure)
The HTML structure includes two main sections: the prompt input form and the image display gallery. Here's the core layout:
<section class="image-generator">
<div class="content">
<h1>AI Image Generator Tool JavaScript</h1>
<p>Convert your text into an image within a second using this JavaScript-powered AI Image Generator tool.</p>
<form class="generate-form">
<input type="text" class="prompt-input" placeholder="Describe what you want to see" required>
<div class="controls">
<select class="img-quantity">
<option value="1">1 Image</option>
<option value="2">2 Images</option>
<option value="3">3 Images</option>
<option value="4" selected>4 Images</option>
</select>
<button type="submit" class="generate-btn">Generate</button>
</div>
</form>
</div>
</section>
<section class="image-gallery">
<div class="img-card"><img src="example.jpg" alt="AI image"></div>
</section>
CSS Code (Styling)
This CSS makes the UI clean, responsive, and mobile-friendly. It uses a modern Google Font and adapts well to different screen sizes.
/* CSS (Link this in a <style> tag or external file) */
body {
font-family: "Poppins", sans-serif;
margin: 0;
padding: 0;
}
.image-generator {
height: 40vh;
background: url("images/bg.jpg") center/cover no-repeat;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
.image-generator::before {
content: "";
position: absolute;
background-color: #121212;
opacity: 0.5;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
.image-gallery {
display: flex;
gap: 15px;
flex-wrap: wrap;
justify-content: center;
}
JavaScript Code (Functionality)
This is the core of the application. It handles form submissions, communicates with the OpenAI API, and updates the UI.
// JavaScript (Place in a <script> tag or external JS file)
const generateForm = document.querySelector(".generate-form");
const generateBtn = generateForm.querySelector(".generate-btn");
const imageGallery = document.querySelector(".image-gallery");
const OPENAI_API_KEY = "YOUR-OPENAI-API-KEY-HERE"; // Replace with your key
const updateImageCard = (imgDataArray) => {
imgDataArray.forEach((imgObject, index) => {
const imgCard = imageGallery.querySelectorAll(".img-card")[index];
const imgElement = imgCard.querySelector("img");
const downloadBtn = imgCard.querySelector(".download-btn");
const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
imgElement.src = aiGeneratedImage;
imgElement.onload = () => {
imgCard.classList.remove("loading");
downloadBtn.setAttribute("href", aiGeneratedImage);
downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
}
});
};
const generateAiImages = async (userPrompt, userImgQuantity) => {
try {
const response = await fetch("https://api.openai.com/v1/images/generations", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify({
prompt: userPrompt,
n: userImgQuantity,
size: "512x512",
response_format: "b64_json"
}),
});
if (!response.ok) throw new Error("Failed to generate AI images.");
const { data } = await response.json();
updateImageCard([...data]);
} catch (error) {
alert(error.message);
} finally {
generateBtn.removeAttribute("disabled");
generateBtn.innerText = "Generate";
}
};
generateForm.addEventListener("submit", (e) => {
e.preventDefault();
const userPrompt = e.target[0].value;
const userImgQuantity = parseInt(e.target[1].value);
generateBtn.setAttribute("disabled", true);
generateBtn.innerText = "Generating...";
const loadingMarkup = Array.from({ length: userImgQuantity }, () =>
`<div class="img-card loading">
<img src="images/loader.svg" alt="loading">
<a class="download-btn" href="#">
<img src="images/download.svg" alt="download icon">
</a>
</div>`
).join("");
imageGallery.innerHTML = loadingMarkup;
generateAiImages(userPrompt, userImgQuantity);
});
How to Get and Use OpenAI API Key
To use the OpenAI API, follow these steps:
- Visit https://platform.openai.com/account/api-keys
- Log in with your OpenAI account
- Click "Create new secret key" and copy it
- Paste it in the JavaScript variable:
const OPENAI_API_KEY = "YOUR-OPENAI-API-KEY-HERE" - Ensure you have at least $5 in credits to generate images
Why Use This Tool?
- No backend required – it's 100% frontend-based using JavaScript
- Fast image generation from prompt descriptions
- Fully responsive and mobile-friendly
- Download buttons included for each generated image
Demo
Please click the button below to view the demo.