Have you ever wanted to create your own website that generates cool pictures using artificial intelligence (AI)? Well, there are popular sites like Midjourney and DALL-E that do just that! They use fancy AI tech to make pictures based on what you describe. But guess what? You can make your own version of these sites too, even if you’re just starting out as a web developer!
Midjourney and DALL-E work like this: you tell them what you want a picture of, and they use their AI brains to make it happen. It’s pretty neat! Now, if you want to make your own AI picture generator, you can do it with some basic web skills like HTML, CSS, and JavaScript.
Today I’ll show you how to build your own AI picture generator website step by step. Don’t worry if you’re new to all this – we’ll start from scratch and use simple JavaScript code. It’s a great way for beginners to practice their web development skills while making something cool and useful!
This specialized AI image generation website will allow users to input their prompt, select the quantity of images they wish to generate, and then initiate the process by clicking the “Generate” button. The AI algorithm will then produce images according to the provided prompt. Each generated image is accompanied by a download button, allowing users to easily save them to their device.
Are You Already Excited to Start?
So let’s not waste the time, here we go
AI Image Generator Website HTML & JavaScript
To build an AI image generator website using HTML, CSS, and vanilla JavaScript, follow these simple step-by-step instructions:
- First, create a folder with any name you like. Then, make the necessary files inside it.
- Create a file called
index.htmlto serve as the main file. - Create a file called
style.cssfor the CSS code. - Create a file called
script.jsfor the JavaScript code. - Finally, download the Images folder and put it in your project directory. This folder contains default showcase images for the website. You can also use your own images.
To start, add the following HTML codes to your index.html file(in my case it is jax.html). These codes include essential HTML markup with different semantic tags, such as div, form, input, button, image, etc., to build the website layout.
<!DOCTYPE html>
<!-- CodeMagnet -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Image Generator</title>
<link rel="stylesheet" href="mystyle.css">
<script src="hey.js" defer></script>
</head>
<body>
<section class="image-generator">
<div class="content">
<h1>AI Image Generator Tool</h1>
<p>Convert your text into an image with Codemagnet-powered AI Image Generator tool.</p>
<form action="#" class="generate-form">
<input class="prompt-input" type="text" 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="C:\Users\Swarna Khushbu\Desktop\Coding\image11.jpg" alt="image"></div>
<div class="img-card"><img src="C:\Users\Swarna Khushbu\Desktop\Coding\image12.jpg" alt="image"></div>
<div class="img-card"><img src="C:\Users\Swarna Khushbu\Desktop\Coding\image13.jpg" alt="image"></div>
<div class="img-card"><img src="C:\Users\Swarna Khushbu\Desktop\Coding\image14.jpg" alt="image"></div>
</section>
</body>
</html>
make sure you replace the path with your own path for the image
Next step is to integrate the provided CSS codes into your style.css file(in my case file name is mystyle.css) to enhance the aesthetics and usability of your AI image generator website. Feel free to modify various CSS attributes like color, background, font, and more to tailor the appearance to your liking. Once you’ve made these adjustments, preview your website in a web browser to observe the changes, now showcasing four preloaded images.
/* Importing Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
.image-generator {
height: 40vh;
display: flex;
align-items: center;
justify-content: center;
position: relative;
background: url("C:/Users/Swarna Khushbu/Desktop/Coding/Designer.png");
background-size: cover;
background-position: center;
}
.image-generator::before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0.5;
background: #121212;
}
.image-generator .content {
position: relative;
color: #fff;
padding: 0 15px;
max-width: 760px;
text-align: center;
}
.image-generator h1 {
font-size: 2.5rem;
font-weight: 700;
}
.image-generator p {
margin-top: 10px;
font-size: 1.35rem;
}
.image-generator .generate-form {
height: 56px;
padding: 6px;
display: flex;
margin-bottom: 15px;
background: #fff;
align-items: center;
border-radius: 30px;
margin-top: 45px;
justify-content: space-between;
}
.generate-form .prompt-input {
width: 100%;
height: 100%;
outline: none;
padding: 0 17px;
border: none;
background: none;
font-size: 1rem;
border-radius: 30px;
}
.generate-form .controls {
display: flex;
height: 100%;
gap: 15px;
}
.generate-form .img-quantity {
outline: none;
border: none;
height: 44px;
background: none;
font-size: 1rem;
}
.generate-form .generate-btn {
font-size: 1rem;
outline: none;
border: none;
font-weight: 500;
color: #fff;
cursor: pointer;
height: 100%;
padding: 0 25px;
border-radius: 30px;
background: #4949E7;
}
.generate-form .generate-btn[disabled] {
opacity: 0.6;
pointer-events: none;
}
.generate-form button:hover {
background: #1d1de2;
}
.image-gallery {
display: flex;
gap: 15px;
padding: 0 15px;
flex-wrap: wrap;
justify-content: center;
margin: 50px auto;
max-width: 1250px;
}
.image-gallery .img-card {
display: flex;
position: relative;
align-items: center;
justify-content: center;
background: #f2f2f2;
border-radius: 4px;
overflow: hidden;
aspect-ratio: 1 / 1;
width: 285px;
}
.image-gallery .img-card img {
height: 100%;
width: 100%;
object-fit: cover;
}
.image-gallery .img-card.loading img {
width: 80px;
height: 80px;
}
.image-gallery .img-card .download-btn {
bottom: 15px;
right: 15px;
height: 36px;
width: 36px;
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
background: #fff;
border-radius: 50%;
position: absolute;
opacity: 0;
pointer-events: none;
transition: 0.2s ease;
}
.image-gallery .img-card .download-btn img {
width: 14px;
height: 14px;
}
.image-gallery .img-card:not(.loading):hover .download-btn {
opacity: 1;
pointer-events: auto;
}
@media screen and (max-width: 760px) {
.image-generator {
height: 45vh;
padding-top: 30px;
align-items: flex-start;
}
.image-generator h1 {
font-size: 1.8rem;
}
.image-generator p {
font-size: 1rem;
}
.image-generator .generate-form {
margin-top: 30px;
height: 52px;
display: block;
}
.generate-form .controls {
height: 40px;
margin-top: 15px;
justify-content: end;
align-items: center;
}
.generate-form .generate-btn[disabled] {
opacity: 1;
}
.generate-form .img-quantity {
color: #fff;
}
.generate-form .img-quantity option {
color: #000;
}
.image-gallery {
margin-top: 20px;
}
.image-gallery .img-card:not(.loading) .download-btn {
opacity: 1;
pointer-events: auto;
}
}
@media screen and (max-width: 500px) {
.image-gallery .img-card {
width: 100%;
}
}
Now lets add the following JavaScript code to your script.js(hey.js in my case) file to make your AI image generator website functional. This code handles various functions, even listeners, input handling, API calls, image rendering, etc. to generate AI images based on user prompts.
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"; // Your OpenAI API key here
let isImageGenerating = false;
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");
// Set the image source to the AI-generated image data
const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
imgElement.src = aiGeneratedImage;
// When the image is loaded, remove the loading class and set download attributes
imgElement.onload = () => {
imgCard.classList.remove("loading");
downloadBtn.setAttribute("href", aiGeneratedImage);
downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
}
});
}
const generateAiImages = async (userPrompt, userImgQuantity) => {
try {
// Send a request to the OpenAI API to generate images based on user inputs
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"
}),
});
// Throw an error message if the API response is unsuccessful
if(!response.ok) throw new Error("Failed to generate AI images. Make sure your API key is valid.");
const { data } = await response.json(); // Get data from the response
updateImageCard([...data]);
} catch (error) {
alert(error.message);
} finally {
generateBtn.removeAttribute("disabled");
generateBtn.innerText = "Generate";
isImageGenerating = false;
}
}
const handleImageGeneration = (e) => {
e.preventDefault();
if(isImageGenerating) return;
// Get user input and image quantity values
const userPrompt = e.srcElement[0].value;
const userImgQuantity = parseInt(e.srcElement[1].value);
// Disable the generate button, update its text, and set the flag
generateBtn.setAttribute("disabled", true);
generateBtn.innerText = "Generating";
isImageGenerating = true;
// Creating HTML markup for image cards with loading state
const imgCardMarkup = Array.from({ length: userImgQuantity }, () =>
`<div class="img-card loading">
<img src="images/loader.svg" alt="AI generated image">
<a class="download-btn" href="#">
<img src="images/download.svg" alt="download icon">
</a>
</div>`
).join("");
imageGallery.innerHTML = imgCardMarkup;
generateAiImages(userPrompt, userImgQuantity);
}
generateForm.addEventListener("submit", handleImageGeneration);
Output:

JavaScript is very important so lets understand the above code by breaking each line of code:
const generateForm = document.querySelector(".generate-form");
This line selects the HTML element with the class “generate-form” and stores it in the variable generateForm.
const generateBtn = generateForm.querySelector(".generate-btn");
This line selects the button element with the class “generate-btn” within the generateForm element and stores it in the variable generateBtn.
const imageGallery = document.querySelector(".image-gallery");
This line selects the HTML element with the class “image-gallery” and stores it in the variable imageGallery.
const OPENAI_API_KEY = "YOUR-OPENAI-API-KEY-HERE"; // Your OpenAI API key here
This line declares a constant variable OPENAI_API_KEY and assigns it a string value representing your OpenAI API key. This key should be replaced with your actual API key.
let isImageGenerating = false;
This line declares a variable isImageGenerating and initializes it with a value of false. This variable will be used to track whether the process of generating images is currently ongoing.
const updateImageCard = (imgDataArray) => {
This line declares a function named updateImageCard that takes an array imgDataArray as its parameter.
imgDataArray.forEach((imgObject, index) => {
This line iterates through each item in the imgDataArray, executing a function for each item. The function receives two parameters: imgObject, representing an image object, and index, representing the index of the current item in the array.
const imgCard = imageGallery.querySelectorAll(".img-card")[index];
This line selects the image card element at the current index within the imageGallery and stores it in the variable imgCard.
const imgElement = imgCard.querySelector("img");
This line selects the img element within the imgCard and stores it in the variable imgElement.
const downloadBtn = imgCard.querySelector(".download-btn");
This line selects the download button within the imgCard and stores it in the variable downloadBtn.
const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
This line constructs a data URI representing the AI-generated image using the Base64-encoded image data (imgObject.b64_json).
imgElement.src = aiGeneratedImage;
This line sets the src attribute of the imgElement to the AI-generated image URI.
imgElement.onload = () => {
This line sets up an event handler that triggers when the image is fully loaded.
imgCard.classList.remove("loading");
This line removes the “loading” class from the imgCard, indicating that the image has finished loading.
downloadBtn.setAttribute("href", aiGeneratedImage);
downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
These lines set the href attribute of the downloadBtn to the AI-generated image URI and specify the filename for downloading.
This pattern continues until the end of the code, handling the generation of AI images based on user input, updating the UI accordingly, and handling errors. The final lines add an event listener to the generateForm element, which triggers the handleImageGeneration function when the form is submitted.





Leave a Reply