Image Generation with ChatGPT: A JavaScript Guide

Ayushmaan Srivastav
3 min readOct 17, 2024

--

Introduction

In this blog post, we will explore how to generate images using prompts provided to ChatGPT and DALL·E via JavaScript. By integrating these powerful AI models, we can create a seamless experience for generating images based on user-defined prompts. Let’s dive into the implementation!

Prerequisites

Before we get started, ensure you have the following:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • An API key from OpenAI to access both ChatGPT and DALL·E models.

Step 1: Obtain Your API Key

  1. Sign Up / Log In to OpenAI: Visit the OpenAI website and create an account if you haven’t already.
  2. Get Your API Key: Navigate to the API section and generate your API key. Keep this key secure, as it will be used for authentication.

Step 2: Setting Up Your Project

Create a new directory for your project and create two files: index.html and app.js.

Directory Structure

/image-generator
├── index.html
└── app.js

Step 3: Creating the HTML Structure

Set up a simple HTML structure in index.html that allows users to input a prompt and generate an image based on that prompt.

HTML Code (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Generator with ChatGPT</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#image-container {
margin-top: 20px;
max-width: 600px;
border: 1px solid #ccc;
padding: 10px;
text-align: center;
}
img {
max-width: 100%;
height: auto;
}
.button {
padding: 10px 20px;
margin: 10px;
cursor: pointer;
}
</style>
</head>
<body>

<h1>Generate Images with ChatGPT</h1>
<input type="text" id="prompt-input" placeholder="Enter a prompt for the image" />
<button id="generate-button" class="button">Generate Image</button>

<div id="image-container"></div>

<script src="app.js"></script>
</body>
</html>

Step 4: Implementing JavaScript Functionality

In the app.js file, we will implement the logic to send a prompt to the DALL·E API and display the generated image.

JavaScript Code (app.js)

const apiKey = 'YOUR_API_KEY'; // Replace with your actual OpenAI API key
const generateButton = document.getElementById('generate-button');
const promptInput = document.getElementById('prompt-input');
const imageContainer = document.getElementById('image-container');

generateButton.addEventListener('click', async () => {
const prompt = promptInput.value;
if (prompt.trim() === "") {
alert("Please enter a valid prompt.");
return;
}

imageContainer.innerHTML = "Generating image...";

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({
prompt: prompt,
n: 1,
size: "1024x1024" // You can adjust the size as needed
})
});

const data = await response.json();
if (data.data && data.data.length > 0) {
const imgUrl = data.data[0].url;
imageContainer.innerHTML = `<img src="${imgUrl}" alt="Generated Image" />`;
} else {
imageContainer.innerHTML = "No image generated. Please try again.";
}
} catch (error) {
console.error('Error:', error);
imageContainer.innerHTML = "An error occurred while generating the image.";
}
});

Step 5: Running Your Application

  1. Insert Your API Key: Open app.js and replace YOUR_API_KEY with your actual OpenAI API key.
  2. Open index.html: Launch the index.html file in your web browser.
  3. Generate an Image: Enter a prompt in the input field and click the “Generate Image” button. The application will process your request and display the generated image.

Conclusion

In this blog post, we’ve successfully built an image generation application that allows users to create images based on prompts using ChatGPT and DALL·E. This project showcases the power of combining JavaScript with advanced AI models to create engaging user experiences.

--

--

Responses (1)