Skip to main content

Command Palette

Search for a command to run...

Generate an Image Using ChatGPT Prompt with JavaScript

Published
3 min read

In this blog post, we'll explore how to use JavaScript to generate images based on prompts given to ChatGPT. By integrating the OpenAI API with a simple web application, you can create an interactive experience that allows users to input text prompts and receive AI-generated images in return.

Prerequisites

Before we dive into the code, ensure you have the following:

  1. OpenAI API Key: You need an API key from OpenAI to access the ChatGPT model and image generation capabilities.

  2. Basic knowledge of HTML and JavaScript: Familiarity with web development concepts will help you understand the implementation better.

Step-by-Step Guide

Step 1: Setting Up Your HTML

First, create a basic HTML structure to take user input and display the generated image.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Generator</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #result { margin-top: 20px; }
    </style>
</head>
<body>
    <h1>AI Image Generator</h1>
    <textarea id="prompt" placeholder="Enter your prompt here..." rows="4" cols="50"></textarea><br>
    <button id="generate-btn">Generate Image</button>
    <div id="result"></div>

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

Step 2: Writing the JavaScript Code

Now, create a file named script.js where we will handle the API calls and the image rendering logic.

document.getElementById("generate-btn").addEventListener("click", async () => {
    const prompt = document.getElementById("prompt").value;
    const apiKey = "YOUR_OPENAI_API_KEY"; // Replace with 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({
                prompt: prompt,
                n: 1,
                size: "1024x1024",
            }),
        });

        const data = await response.json();
        if (data.data && data.data.length > 0) {
            const imageUrl = data.data[0].url;
            document.getElementById("result").innerHTML = `<img src="${imageUrl}" alt="Generated Image" style="max-width: 100%;">`;
        } else {
            document.getElementById("result").innerText = "No image generated.";
        }
    } catch (error) {
        console.error("Error generating image:", error);
        document.getElementById("result").innerText = "Error generating image. Please try again.";
    }
});

Step 3: Explanation of the Code

  • HTML Structure: The HTML provides a textarea for users to input their prompts, a button to trigger the image generation, and a div to display the resulting image.

  • JavaScript Logic: When the button is clicked, we capture the user input and send a POST request to the OpenAI API, specifically the image generation endpoint.

  • API Key: Remember to replace "YOUR_OPENAI_API_KEY" with your actual OpenAI API key.

  • Handling the Response: Upon a successful response, we extract the generated image URL and display it in the result div.

Step 4: Testing Your Application

  1. Open your HTML file in a web browser.

  2. Enter a prompt in the textarea (e.g., "A futuristic city at sunset").

  3. Click the "Generate Image" button and wait for the image to appear.

Conclusion

You have successfully created a simple web application that generates images based on user prompts using ChatGPT and JavaScript! This approach can be expanded in various ways, such as allowing users to customize image dimensions or adding styles to the images.

Feel free to experiment with different prompts and enhance the functionality as per your requirements!


This simple project combines front-end web development with powerful AI capabilities, showcasing how you can create engaging applications that leverage modern technology.

References

For further details, you can check the OpenAI API documentation for more information about the image generation capabilities.

More from this blog

Amazon S3 Storage Classes

43 posts