"Creating an AI image generator website with HTML, CSS, and JavaScript."
Already we build a most advanced AI-generated images from text using python. Those who wants to build an AI-generated images from text using python can visit this page: How to Generate Images from Text Using Python. Now it’s time to build our most advanced AI-generated images from text using HTML/CSS and JavaScript. This includes many steps, where we combine HTML/CSS and JavaScript to create our wonderful AI Image Generator Website. On this Application, you can enter text prompts and get AI-generated images as a result. Let’s explore each part and the entire process of constructing such a website in detail.
Generating images from text prompts usually relies on an external API, such as OpenAI’s DALL-E or a other similar service, to perform its core function. These APIs utilize advanced machine learning models trained to understand and generate images from textual descriptions. Here’s a more in-depth explanation of the process:
First, create a new folder for your project. Inside this folder, create three files: index.html, style.css, and script.js. Now start Write coding on the respective files.
Below is a more detailed example of how you can implement such a web application using HTML, CSS, and JavaScript:
Let’s break down the code step by step, including both the HTML structure and the JavaScript functionality.
<strong><!DOCTYPE html>
<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="styles.css">
</head>
<body></strong>
styles.css for styling the page. <strong> <div class="container">
<h1>AI Image Generator</h1>
<form id="imageForm">
<label for="prompt">Enter your prompt:</label>
<input type="text" id="prompt" name="prompt" required>
<button type="submit">Generate Image</button>
</form>
...
</div>
<script src="scripts.js"></script>
</body>
</html></strong>
container to center and style the content.scripts.js.<strong><div id="imageOptions">
<label for="imageCount">Number of Images:</label>
<input type="number" id="imageCount" name="imageCount" min="1" value="1">
<label for="imageSize">Image Size:</label>
<select id="imageSize" name="imageSize">
<option value="512x512">512x512</option>
<option value="1024x1024">1024x1024</option>
<option value="2048x2048">2048x2048</option>
</select>
</div></strong><strong><div id="result">
<h2>Generated Images:</h2>
<div id="generatedImagesContainer"></div>
</div>
<button id="clearButton">Clear Images</button>
<div id="imageFilters">
<h2>Image Filters:</h2>
<button id="grayscaleButton">Grayscale</button>
<button id="sepiaButton">Sepia</button>
<button id="blurButton">Blur</button>
</div>
<div id="imageEnhancements">
<h2>Image Enhancements:</h2>
<label for="brightness">Brightness:</label>
<input type="range" id="brightness" name="brightness" min="-100" max="100" value="0">
<label for="contrast">Contrast:</label>
<input type="range" id="contrast" name="contrast" min="-100" max="100" value="0">
<label for="saturation">Saturation:</label>
<input type="range" id="saturation" name="saturation" min="-100" max="100" value="0">
</div>
<div id="shareButtons">
<h2>Share Image:</h2>
<button id="facebookShare">Share on Facebook</button>
<button id="twitterShare">Share on Twitter</button>
</div></strong>This part shows the images that are generated based on certain settings or inputs. Right now, it’s just a container where the images will appear.
This button clears all the images currently displayed in the “Generated Images” section.
Here, you have options to apply different filters to the images. These filters include making the images grayscale, sepia-toned, or blurred.
This section lets you adjust various aspects of the images to enhance them. You can change the brightness, contrast, and saturation using sliders.
Finally, there are buttons provided to easily share the images on social media platforms like Facebook and Twitter. Just click the respective buttons to share the images on those platforms.
Overall, this setup gives you control over generating, modifying, and sharing images right from this interface. You can adjust the appearance of the images and then easily share them with others.
I provide complete coding at the end of this article you can refer that for styles.css
The CSS styles the webpage, including the layout, button styles, and form elements. Notable styles:
The JavaScript handles form submission, image generation, applying filters, enhancements, and sharing functionality.
<strong>document.getElementById('imageForm').addEventListener('submit', async function(event) {</strong>This line sets up an event listener for the form with the ID imageForm. When the form is submitted, it triggers the function defined here.
<strong>event.preventDefault();</strong>This prevents the default behavior of the form submission, which would normally reload the page.
<strong>const prompt = document.getElementById('prompt').value;
const imageCount = document.getElementById('imageCount').value;
const imageSize = document.getElementById('imageSize').value;
const generatedImagesContainer = document.getElementById('generatedImagesContainer');</strong>These lines retrieve the values from the input fields for the prompt, number of images, and image size. They also get a reference to the container where the generated images will be displayed.
<strong>const apiKey = 'YOUR_OPENAI_API_KEY';</strong>This line defines the API key required to authenticate with the OpenAI API. (You need to replace 'YOUR_OPENAI_API_KEY' with your actual API key.)
<strong>try {
const response = await fetch('https://api.openai.com/v1/images/generations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'image-alpha-001',
prompt: prompt,
n: parseInt(imageCount),
size: imageSize
})
});</strong>This block tries to send a POST request to the OpenAI API to generate images based on the user’s input. It includes:
fetch function to send the request.method: 'POST' to specify the request type.headers to set the content type and authorization with the API key.body to include the prompt, number of images, and size in JSON format.<strong>if (!response.ok) {
throw new Error('Network response was not ok');
}</strong>This checks if the response from the API is okay. If not, it throws an error.
<strong>const data = await response.json();
generatedImagesContainer.innerHTML = '';
data.data.forEach((image, index) => {
const imgElement = document.createElement('img');
imgElement.src = image.url;
imgElement.alt = `Generated Image ${index + 1}`;
const imageContainer = document.createElement('div');
imageContainer.classList.add('generated-image-container');
imageContainer.appendChild(imgElement);
generatedImagesContainer.appendChild(imageContainer);
});</strong>This block processes the response data:
img element for each, sets the src attribute to the image URL, and adds it to the container.<strong>} catch (error) {
console.error('Error:', error);
alert('Failed to generate image. Please try again later.');
}</strong>If there is an error during the process (e.g., network issues, API problems), it catches the error, logs it to the console, and shows an alert to the user.
In summary, this script listens for a form submission, prevents the default action, gathers user inputs, sends a request to the OpenAI API to generate images, and then displays those images in a specified container. If anything goes wrong, it handles the error gracefully by logging it and alerting the user.
<strong>document.getElementById('clearButton').addEventListener('click', function() {
document.getElementById('generatedImagesContainer').innerHTML = '';
});</strong>Event Listener: Clears the generated images container when the button is clicked.
<strong>document.getElementById('grayscaleButton').addEventListener('click', function() {
applyFilter('grayscale(100%)');
});
document.getElementById('sepiaButton').addEventListener('click', function() {
applyFilter('sepia(100%)');
});
document.getElementById('blurButton').addEventListener('click', function() {
applyFilter('blur(5px)');
});</strong>Filter Buttons: Apply grayscale, sepia, and blur filters to images by calling applyFilter with respective CSS filter values.
grayscaleButton is clicked.applyFilter function is called with the argument 'grayscale(100%)'.applyFilter function applies a grayscale effect to the images, making them appear black and white.sepiaButton is clicked.applyFilter function is called with the argument 'sepia(100%)'.applyFilter function applies a sepia effect to the images, giving them a warm, brownish tone like an old photograph.blurButton is clicked.applyFilter function is called with the argument 'blur(5px)'.applyFilter function applies a blur effect to the images, making them appear fuzzy or out of focus.applyFilter FunctionAlthough the code for applyFilter is not provided, we can infer what it might do. The applyFilter function likely applies the specified CSS filter to all the images in the container. Here’s a possible implementation:
<strong>function applyFilter(filter) {
const images = document.querySelectorAll('#generatedImagesContainer img');
images.forEach(image => {
image.style.filter = filter;
});
}</strong>This function:
img elements within the generatedImagesContainer.By clicking the respective buttons, users can apply different visual effects to the generated images.
<strong>document.getElementById('brightness').addEventListener('input', function() {
applyEnhancement();
});</strong>This line adds an event listener to the brightness input slider. Whenever the value of this slider changes (input event), it triggers a function called applyEnhancement().
<strong>document.getElementById('contrast').addEventListener('input', function() {
applyEnhancement();
});</strong>Similarly, this line attaches an event listener to the contrast input slider. When the value of this slider changes, it also triggers the applyEnhancement() function.
<strong>document.getElementById('saturation').addEventListener('input', function() {
applyEnhancement();
});</strong>Likewise, this line adds an event listener to the saturation input slider. When the value of this slider changes, it also triggers the applyEnhancement() function.
input event is fired.applyEnhancement() function.input event is fired.applyEnhancement() function.input event is fired.applyEnhancement() function.applyEnhancement FunctionAlthough the code for applyEnhancement is not provided, we can assume its purpose. The applyEnhancement function is likely responsible for applying the enhancements specified by the user (brightness, contrast, saturation) to the images. Here it is:
<strong>function applyEnhancement() {
const brightnessValue = document.getElementById('brightness').value;
const contrastValue = document.getElementById('contrast').value;
const saturationValue = document.getElementById('saturation').value;
const images = document.querySelectorAll('#generatedImagesContainer img');
images.forEach(image => {
image.style.filter = `brightness(${brightnessValue}%) contrast(${contrastValue}%) saturate(${saturationValue}%)`;
});
}</strong>This function:
img elements within the generatedImagesContainer.By moving the sliders, users can adjust the appearance of the images in real-time, controlling their brightness, contrast, and saturation.
<strong>document.getElementById('facebookShare').addEventListener('click', function() {
shareImage('facebook');
});
document.getElementById('twitterShare').addEventListener('click', function() {
shareImage('twitter');
});</strong>shareImage() with the respective platform name when the user clicks on a share button.Certainly! Let’s break down the application flow in simple terms:
This application essentially provides users with a fun and interactive way to create, modify, and share images based on their own descriptions or ideas. It’s like having a creative tool at their fingertips, powered by advanced AI technology.
https://api.example.com/generate-image with the actual endpoint of your AI image generation service.You can try this code on our HTML/CSS/JavaScript Compiler here before you try this on actual project
<strong><!DOCTYPE html>
<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="styles.css">
</head>
<body>
<div class="container">
<h1>AI Image Generator</h1>
<form id="imageForm">
<label for="prompt">Enter your prompt:</label>
<input type="text" id="prompt" name="prompt" required>
<button type="submit">Generate Image</button>
</form>
<div id="imageOptions">
<label for="imageCount">Number of Images:</label>
<input type="number" id="imageCount" name="imageCount" min="1" value="1">
<label for="imageSize">Image Size:</label>
<select id="imageSize" name="imageSize">
<option value="512x512">512x512</option>
<option value="1024x1024">1024x1024</option>
<option value="2048x2048">2048x2048</option>
</select>
</div>
<div id="result">
<h2>Generated Images:</h2>
<div id="generatedImagesContainer"></div>
</div>
<button id="clearButton">Clear Images</button>
<div id="imageFilters">
<h2>Image Filters:</h2>
<button id="grayscaleButton">Grayscale</button>
<button id="sepiaButton">Sepia</button>
<button id="blurButton">Blur</button>
</div>
<div id="imageEnhancements">
<h2>Image Enhancements:</h2>
<label for="brightness">Brightness:</label>
<input type="range" id="brightness" name="brightness" min="-100" max="100" value="0">
<label for="contrast">Contrast:</label>
<input type="range" id="contrast" name="contrast" min="-100" max="100" value="0">
<label for="saturation">Saturation:</label>
<input type="range" id="saturation" name="saturation" min="-100" max="100" value="0">
</div>
<div id="shareButtons">
<h2>Share Image:</h2>
<button id="facebookShare">Share on Facebook</button>
<button id="twitterShare">Share on Twitter</button>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html></strong><strong>body {
font-family: Arial, sans-serif;
background-color: #ffffff;
display: flex;
justify-content: center;
align-items: center;
height: 99vh;
margin: 0;
}
.container {
text-align: center;
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 600px;
width: 100%;
overflow: auto;
height: 90vh;
}
form {
margin-bottom: 20px;
}
input[type="text"], input[type="number"], select {
width: 80%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 20px;
border: none;
background: #5cb85c;
color: #fff;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #4cae4c;
}
#result {
margin-top: 20px;
}
#generatedImagesContainer {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 20px;
}
.generated-image-container {
border: 1px solid #ccc;
padding: 10px;
border-radius: 8px;
width: 45%;
}
.generated-image-container img {
max-width: 100%;
height: auto;
}
#clearButton {
margin-top: 20px;
background-color: #d9534f;
}
#imageOptions, #imageFilters, #imageEnhancements, #shareButtons {
margin-top: 20px;
border-top: 1px solid #ccc;
padding-top: 20px;
}
#imageOptions label, #imageFilters label, #imageEnhancements label {
display: block;
margin-bottom: 5px;
}
#imageOptions select {
margin: 10px 0;
}
#imageEnhancements input[type="range"] {
margin: 5px 0;
width: 80%;
}
#shareButtons button {
margin-top: 10px;
}</strong><strong>document.getElementById('imageForm').addEventListener('submit', async function(event) {
event.preventDefault();
const prompt = document.getElementById('prompt').value;
const imageCount = document.getElementById('imageCount').value;
const imageSize = document.getElementById('imageSize').value;
const generatedImagesContainer = document.getElementById('generatedImagesContainer');
// Replace this with your actual OpenAI API key
const apiKey = 'YOUR_OPENAI_API_KEY';
try {
const response = await fetch('https://api.openai.com/v1/images/generations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'image-alpha-001',
prompt: prompt,
n: parseInt(imageCount), // Number of images to generate
size: imageSize // Desired size of the image
})
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
// Clear previous generated images
generatedImagesContainer.innerHTML = '';
// Append each generated image to the container
data.data.forEach((image, index) => {
const imgElement = document.createElement('img');
imgElement.src = image.url;
imgElement.alt = `Generated Image ${index + 1}`;
const imageContainer = document.createElement('div');
imageContainer.classList.add('generated-image-container');
imageContainer.appendChild(imgElement);
generatedImagesContainer.appendChild(imageContainer);
});
} catch (error) {
console.error('Error:', error);
alert('Failed to generate image. Please try again later.');
}
});
document.getElementById('clearButton').addEventListener('click', function() {
document.getElementById('generatedImagesContainer').innerHTML = '';
});
document.getElementById('grayscaleButton').addEventListener('click', function() {
applyFilter('grayscale(100%)');
});
document.getElementById('sepiaButton').addEventListener('click', function() {
applyFilter('sepia(100%)');
});
document.getElementById('blurButton').addEventListener('click', function() {
applyFilter('blur(5px)');
});
document.getElementById('brightness').addEventListener('input', function() {
applyEnhancement();
});
document.getElementById('contrast').addEventListener('input', function() {
applyEnhancement();
});
document.getElementById('saturation').addEventListener('input', function() {
applyEnhancement();
});
document.getElementById('facebookShare').addEventListener('click', function() {
shareImage('facebook');
});
document.getElementById('twitterShare').addEventListener('click', function() {
shareImage('twitter');
});
function applyFilter(filter) {
const images = document.querySelectorAll('#generatedImagesContainer img');
images.forEach(img => {
img.style.filter = filter;
});
}
function applyEnhancement() {
const brightness = document.getElementById('brightness').value;
const contrast = document.getElementById('contrast').value;
const saturation = document.getElementById('saturation').value;
const filter = `brightness(${100 + parseInt(brightness)}%) contrast(${100 + parseInt(contrast)}%) saturate(${100 + parseInt(saturation)}%)`;
applyFilter(filter);
}
function shareImage(platform) {
const images = document.querySelectorAll('#generatedImagesContainer img');
images.forEach(img => {
const imageUrl = img.src;
let url;
if (platform === 'facebook') {
url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(imageUrl)}`;
} else if (platform === 'twitter') {
url = `https://twitter.com/intent/tweet?url=${encodeURIComponent(imageUrl)}`;
}
window.open(url, '_blank');
});
}</strong>Open index.html in your browser, and you should see your AI image generator website. Clicking the “Generate Image” button should display a placeholder image. Replace the ‘YOUR_OPENAI_API_KEY’ with the actual OPENAI_API_KEY .
You’ve successfully built your own AI image generator website using HTML, CSS, and JavaScript. Feel free to enhance the functionality by integrating advanced machine learning models or adding more features like image customization options. This project serves as a great starting point for exploring the intersection of web development and artificial intelligence.
To obtain access to an actual AI image generator API, you can use services provided by companies that offer AI and machine learning APIs. Some popular options include OpenAI’s DALL-E, Stability AI’s Stable Diffusion, and other similar services. Below are a few suggestions:
OpenAI provides an API for DALL-E, which is capable of generating images from textual descriptions. You can access it through OpenAI’s API platform.
Steps to get started:
Stable Diffusion is an open-source AI model for generating images from text prompts. It’s available via various platforms and APIs.
Steps to get started:
DeepAI offers a variety of image generation models accessible via a straightforward API.
Steps to get started:
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.
View Comments