Image Generator Using ChatGPT and DALL·E

Image Generator Using ChatGPT and DALL·E

Introduction

This documentation outlines the steps to create a web application that generates images based on user-defined prompts using OpenAI's ChatGPT and DALL·E APIs. By integrating these models with JavaScript, users can enjoy a seamless image generation experience.

Prerequisites

Before starting the implementation, 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 don’t already have one.

  2. Get Your API Key: Navigate to the API section of your OpenAI account and generate your API key. Keep this key secure, as it will be used for authentication.

Step 2: Setting Up Your Project

  1. Create a new directory for your project. You can name it image-generator.

  2. Inside this directory, create two files:

    • index.html

    • 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, 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 project, we have successfully built an image generation application that allows users to create images based on prompts using ChatGPT and DALL·E. This integration showcases the power of combining JavaScript with advanced AI models to create engaging user experiences. By utilizing OpenAI's APIs, developers can enhance their applications with creative functionalities.

Feel free to customize the design and functionality to suit your needs! Happy coding!