How to make an AI Image Generator yourself for free(easy)🖼️
Tags: ai, tutorial, webdev, openai
Published: 2023-02-25 23:59:24

Note: This tutorial is heavily inspired by a paid course created by Fireship: [Link to paid course](https://fireship.io/courses/js/)

Today, we'll be making a fully working AI Image generator with pure Javascript. Be realistic, we won't be able to train our own AI with billions of images for free, so we'll be using OpenAI's pretrained dataset.

Please be aware that this course isn't aimed for pure beginners, if you are reading this, please make sure you have some basic understanding of Javascript and using the Terminal.

## Project Set Up

First, be aware that I'll be using VSCode as my IDE, you can [download](https://code.visualstudio.com/) it to follow along.

To get started, create a new folder, and open the folder up in VSCode. Name the folder whatever you want, but remember the name.

Opening a folder: File>Open Folder

![Creating a new folder in VSCode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6fotddzb4u44md739pl2.png)

After you got a folder open, select Terminal>New Terminal from the top of the screen. 

In the new terminal, type the following command:
`npm init vite@latest imgtutorial`

Feel free to replace imgtutorial with any name you want. Now you would be prompted to select a framework, just hit enter, do the same when it tells you to select a variant.


![Creating a new Terminal and Init Vite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9v5y103j7qme13dqksl.png)

Now type the following commands in order:

`cd imgtutorial
npm install
`

After that, just to check that you got everything right, type `npm run dev` which should start up your frontend server. You can either type the link manually into your search engine, or control(command on mac)+click the link shown.

![Vite Setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hr46nzspgzsze225mpav.png)



If you see a demo website like the one below, you did it right.

![Demo Frontend](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0c4zqyeao58jtzoshptr.png)

## OpenAI Account Creation

Now that we got our frontend setup, let's take a break from coding and set up OpenAI. 

To get started, go to [OpenAI](https://openai.com/api/) and create an account. After that, click on your [profile](https://platform.openai.com/account/api-keys) on the top right corner, and select view API keys.


![OpenAI API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inn1zz0d26bq6v7ackvs.png)

Then click Create New Secret Key, and store the key shown somewhere secure. It is REALLY important that you do not tell anyone your API key.

![Generated API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezmrg3jieip9bu2haanv.png)

Now to store your API key in your project, head back to VSCode, and click once on the folder you've just created with the Command Prompt, then select the create file icon.


![Creating a .env file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hyu8b9yajr7wtzxq3dzn.png)

Now in the window, type in .env.

![Finnished enviorment creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iw52vmxlxtqn9snt6b4h.png)

Now type the following code into your .env file, replacing yourkey with your OpenAI API key. 

`OPENAI="your key"`

Now we'll create another Terminal window exactly the same way we did before. You should click Terminal>New Terminal. In your new terminal, type the following command, replacing with imgtutorial with the name of your folder.

`cd imgtutorial`

Now inside your sub folder, type in the following command to install some more dependencies.

`npm i dotenv express cors openai`

After this, you should have your OpenAI fully setup and ready to use in your backend code.

## Backend Coding

Now as we did before, we'll create a new file called server.js. Again, click on your subfolder, and then click on the add file icon.

![Creating the Server.js file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpjrhqaf763gth74fh8j.png)

Then in the box, type server.js:

![Naming the new file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2a7gjhq4jqs86u91f6g.png)

Inside server.js, copy the following code:

```
import * as dotenv from 'dotenv';
dotenv.config();

import { Configuration, OpenAIApi } from 'openai';

const configuration = new Configuration({
  apiKey: process.env.OPENAI,
});

const openai = new OpenAIApi(configuration);

import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());
app.use(express.json());

app.post('/dream', async (req, res) => {
    const prompt = req.body.prompt;

    const aiResponse = await openai.createImage({
      prompt,
      n: 1,
      size: '1024x1024',
    });

    const image = aiResponse.data.data[0].url;
    res.send({ image });
});

app.listen(8080, () => console.log('make art on http://localhost:8080/dream'));
```

Now in the same terminal window you added your dependencies, type in the following command:

`node server.js`

![Creating Backend for AI Img Gen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0w7o5pm51l8uoqxvmko.png)

This should return you with an URL, but you can ignore it. Anyway, now we got our backend set up and complete!

## Frontend Coding

We are now almost finnished with our AI image generator, the last step is to create the frontend, which is accturally the easiest step.

First, go to the HTML file and copy this in:


![HTML file location](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tbyva0ae794x69jxkelc.png)

Copy the following:

```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <main>
      <h1>AI Photo Generator</h1>
      

      <div id="result">
        Image will appear here
      </div>

      <form>
        <label for="prompt">Prompt</label>
        <textarea name="prompt" maxlength="160"></textarea>

        <button type="submit">Dream</button>
      </form>
    </main>

    <script type="module" src="/main.js"></script>
  </body>
</html>
```

Then go to the main.js file and copy this in:

![Javascript File Location](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/thypopm2ozr5j8mwvx3q.png)

Copy the following:



```
import './style.css';

const form = document.querySelector('form');

form.addEventListener('submit', async (e) => {
    e.preventDefault();

    const data = new FormData(form);

    const response = await fetch('http://localhost:8080/dream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt: data.get('prompt'),
      }),
    });

    const { image } = await response.json();

    const result = document.querySelector('#result');
    result.innerHTML = `<img src="${image}" width="512" />`;
});
```

Then go to the style.css and copy this in:

![StyleCSS location](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ce7qswdjxl59bnzem4zg.png)

Copy the following:


```
@import url('https://fonts.googleapis.com/css2?family=Poppins&family=Rubik+Glitch&family=Rubik+Microbe&display=swap');
body {
  background-color: #0b0b0e;
  color: white;
  font-family: 'Poppins', sans-serif;
  margin-top: 50px;
}

main {
 display: grid;
 place-items: center;
}

h1 {
  font-family: 'Rubik Microbe', cursive;
  font-weight: 400;
  font-size: 5rem;
}

#result {
  aspect-ratio: 1/1;
  max-width: 512px;
  width: 100%;
  background: #3a3a43;
  display: flex;
  justify-content: center;
  align-items: center;

}

form {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  max-width: 512px;
  margin-top: 2rem;
}

textarea {
  width: 100%;
  height: 100px;
  margin: 10px 0;
  font-size: 1.5rem;
}

button {
  width: 100%;
  height: 50px;
  background-color: #1b1b1e;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  text-transform: uppercase;
  font-weight: 600;
  margin-bottom: 50px;
}

button:hover {
  background-color: #2b2b2e;
}

.hidden {
  display: none;
}


.spinner {
  animation: spin 1s linear infinite;
  display: inline-block;
}


@keyframes spin {
  from {transform:rotate(0deg);}
  to {transform:rotate(360deg);}
}
```

Now you are all set! We just need to run our frontend code again and we got a complete image generator! 

## Running your Project

This is the final step in this course. Under the terminal tab, delete all currently running terminals.

![Delete terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cbykzrh2ije5igtgu61f.png)

To delete a terminal, hover over it, then select the trash icon, do this with all the terminals available. 

Now create a new one(terminal>new terminal) and do the following:

1. Type this: `cd imgtutorial` Replacing imgtutorial with whatever you named your sub folder.

2. Then Type: `node server.js`

You should see results similar to this.
![Backend Results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ler3kisvk94zq8ope4tc.png)

Now create another terminal(terminal>new terminal) and do the following:

1. Type this: `cd imgtutorial` Replacing imgtutorial with whatever you named your sub folder.

2. Then type `npm run dev`

You should see results like the following:

![Frontend Results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rw1j3v3a6xqxmeva2agp.png)

Now to access your AI image generator, copy the link generated and access it in a browser.

In the prompt area, describe the image you want it to generate, then click dream. Wait for 1-2 minute and you should see a generated image!


![How to use AI img gen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21hsfgj7thpcflc1i6u3.png)


## Conclusion:

This is quite a complex tutorial, and you probibally will experience some bugs throughout completing this project. But I'm here to help, just message me and I'll sort your issue out:

My Email: support@freetechnologyhelp.com

If you enjoyed this tutorial, chances are that you'll enjoy my other tutorials too! So here are some ways you can learn more from me:

1. Here on dev.to
2. On my [twitter account](https://twitter.com/acode123)
3. From my [website](https://freetechnologyhelp.com/)