How to Build an Image Generator Site Using AI Technology

Due to their capacity to use artificial intelligence (AI) to create unique and artistic graphics, websites such as Midjourney and DALL-E have been increasingly popular in the last few months or years. Have you ever thought about making your own AI picture generating website if you’re a novice web developer? The good news is that you too can create a website similar to Midjourney or DALL-E using just HTML, CSS, and JavaScript.

These two websites, Midjourny and DALL-E, are artificial intelligence (AI) picture generators. Based on text descriptions, they generate graphics using a machine-learning algorithm. These websites allow users to enter their preferred picture prompt, and they will produce an image that corresponds with the description.

I’ll walk you through the process of creating your own website that uses HTML, CSS, and JavaScript to create AI graphics in this blog article. All of the website’s components will be created from scratch using only JavaScript. Therefore, as a novice, you may obtain real-world experience by using your newly acquired HTML, CSS, and JavaScript knowledge in actual online applications.

Users input their question, choose how many photographs they wish to produce, and then click the “Generate” button on this bespoke AI image production website. After that, the AI will produce graphics in response to human input. The user may click the proper download button for each image to download it.

Video Tutorial of AI Image Generator HTML and JavaScript

Source: CodingNepal

The aforementioned YouTube video might be a great resource if you like to learn through video instructions. To make creating your own AI picture generating website straightforward and simple to understand, I’ve broken down each line of code and added insightful commentary in the video.

You can read this post through to the end if you like reading blog entries or would want a step-by-step tutorial for this project. You will have your own AI picture generating website at the conclusion of this post, which you can share with your friends and add to your portfolio.

Steps to Build 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.html to serve as the main file.
  • Create a file called style.css for the CSS code.
  • Create a file called script.js for 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. 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>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI Image Generator HTML CSS and JavaScript | CodingNepal</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js" defer></script>
</head>
<body>
  <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 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="images/img-1.jpg" alt="image"></div>
    <div class="img-card"><img src="images/img-2.jpg" alt="image"></div>
    <div class="img-card"><img src="images/img-3.jpg" alt="image"></div>
    <div class="img-card"><img src="images/img-4.jpg" alt="image"></div>
  </section>
</body>
</html>

Next, update your style with the following CSS codes.css file to enhance the aesthetics and usability of your AI picture generating website. To give your website a unique look, you may alter the many CSS attributes, like color, background, font, and so on. You may now view your AI picture generator website with four prepared photos if you load the page in your browser.

/* 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("images/bg.jpg");
  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%;
  }
}

Lastly, update your script with the JavaScript code that follows.js file to enable functionality on your AI picture generating website. In order to create AI graphics in response to user input, this code manages a variety of tasks, including listeners, input management, API calls, image rendering, etc.

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);

Please be aware that since you haven’t included your API key in the OPENAI_API_KEY variable, your website is still unable to produce AI pictures. OpenAI API is what we’re utilizing to create the photos. Thus, register for an account at https://platform.openai.com/account/api-keys in order to receive a free API key from OpenAI.

Recall that you will receive a $5 credit for using the API when you join up for OpenAI. To continue using the API, you will need to either establish a new account with a new number or purchase an account if your current one is older than three months or the credit runs out. The account’s use page contains information about your API usage and expiration date.

I suggest viewing the video instruction above, reading the code comments, and playing around with the code to get a better understanding of the JavaScript code.

Wrap-up and parting remarks
To sum up, creating your own AI-powered picture creation website is not only a fun project but also a great way to use your web development expertise on projects that are becoming more and more popular in the modern digital world.

Conclusion and Final words

In conclusion, building your own AI-powered image generation website is not just an exciting project but also a valuable opportunity to apply your web development skills to projects that are increasingly in demand in today’s digital world.

I think you’ve successfully made your own special form of an AI picture generator by following the instructions in this post. To improve your website even more, don’t be afraid to try out new features and layouts. I advise you to attempt building a chatbot, image search engine, or ChatGPT clone in order to hone your abilities even more.

Click the Download button to get the project’s source code files for free, in case you run into any issues when creating your AI-powered picture creation website. Recall that the OPENAI_API_KEY variable in the script.js file requires your valid OpenAI API key, which you must provide after downloading the code.

Bipul author of nerdy tutorial
Bipul

Hello my name is Bipul, I love write solution about programming languages.

Articles: 146

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *