Welcome folks today in this blog post we will be building an AI Image Generator in browser using node.js and express. For this application we will be using the OpenAI API to get the random created images by AI. All the full source code of the application is given below.
Get Started
In order to get started you need to make a node.js
project using the below command as shown below
npm init -y
npm i express
npm i dotenv
npm i openai
The directory structure of the app will look something like this
Now first of all guys make a .env file and copy paste the below code
.env
1 2 |
PORT=5000 OPENAI_API_KEY='####apikey####' |
Here in the above code you need to copy paste your api key. You can get your own api key by going to https://beta.openai.com/account/api-keys
After installing these dependencies you need to make the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const path = require('path'); const express = require('express'); const dotenv = require('dotenv').config(); const port = process.env.PORT || 5000; const app = express(); // Enable body parser app.use(express.json()); app.use(express.urlencoded({ extended: false })); // Set static folder app.use(express.static(path.join(__dirname, 'public'))); app.use('/openai', require('./routes/openaiRoutes')); app.listen(port, () => console.log(`Server started on port ${port}`)); |
As you can see in the above code we are including the express library and making a new express web server and starting on the port number which is there inside the .env file. We are also passing some middleware functions for json and urlencoded which is necessary while working with html5 forms. And then we are setting the public directory as static because in that we will be storing the html and javascript files. We are using the static()
method to make the public directory as static in express. And then we are importing the files which contain all the routes and then including it using the use()
method.
Now we need to create the routes folder and inside that we need to define the openaiRoutes.js
file and copy paste the below code
routes/openaiRoutes.js
1 2 3 4 5 6 7 |
const express = require('express'); const { generateImage } = require('../controllers/openaiController'); const router = express.Router(); router.post('/generateimage', generateImage); module.exports = router; |
As you can see we are importing the express and also we need to import the controller
file of this node.js project basically that file will contain all the logic behind this application. And then we are initializing the router and then we are writing the post request to the /generateimage
route and here we are executing the method called generateImage
which is imported from the controller file. And then we are exporting the router using module.exports()
method.
And now we need to create the public
directory and inside it we need to make the index.html
file and copy paste the following code. And also make a js
folder and inside it we will be creating the main.js
file as shown below
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="js/main.js" defer></script> <title>OpenAI Image Genrator</title> </head> <body> <header> <div class="navbar"> <div class="logo"> <h2>OpenAI Image Genrator</h2> </div> <div class="nav-links"> <ul> <li> <a href="https://beta.openai.com/docs" target="_blank" >OpenAI API Docs</a > </li> </ul> </div> </div> </header> <main> <section class="showcase"> <form id="image-form"> <h1>Describe An Image</h1> <div class="form-control"> <input type="text" id="prompt" placeholder="Enter Text" /> </div> <!-- size --> <div class="form-control"> <select name="size" id="size"> <option value="small">Small</option> <option value="medium" selected>Medium</option> <option value="large">Large</option> </select> </div> <button type="submit" class="btn">Generate</button> </form> </section> <section class="image"> <div class="image-container"> <h2 class="msg"></h2> <img src="" alt="" id="image" /> </div> </section> </main> <div class="spinner"></div> </body> </html> |
In the above code we have the simple input field where we allow the user to enter the keyword based upon which the image will be generated by automation. And then we have the select field where we select the size of the image. And now if you open the index.html
in browser you will see the below result
And now we will be writing the javascript code inside the main.js
file as shown below
js/main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
function onSubmit(e) { e.preventDefault(); document.querySelector('.msg').textContent = ''; document.querySelector('#image').src = ''; const prompt = document.querySelector('#prompt').value; const size = document.querySelector('#size').value; if (prompt === '') { alert('Please add some text'); return; } generateImageRequest(prompt, size); } async function generateImageRequest(prompt, size) { try { const response = await fetch('/openai/generateimage', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ prompt, size, }), }); if (!response.ok) { throw new Error('That image could not be generated'); } const data = await response.json(); // console.log(data); const imageUrl = data.data; document.querySelector('#image').src = imageUrl; } catch (error) { document.querySelector('.msg').textContent = error; } } document.querySelector('#image-form').addEventListener('submit', onSubmit); |
As you can see in the above javascript code we have written the code for onSubmit() which will automatically gets called when the form submits and inside it the event object is passed and using this we can get the values that the user has entered inside the form. And based upon that we are making a post request using the fetch api in browser using javascript. And after getting the image we are displaying the image in the browser. Now we need to handle this fetch post
request to generate image based upon the description of the image.
Now we need to create the controllers
directory and inside it we need to make the openaiController.js
file and copy paste the below code
controllers/openaiController.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
const { Configuration, OpenAIApi } = require('openai'); const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration); const generateImage = async (req, res) => { const { prompt, size } = req.body; const imageSize = size === 'small' ? '256x256' : size === 'medium' ? '512x512' : '1024x1024'; try { const response = await openai.createImage({ prompt, n: 1, size: imageSize, }); const imageUrl = response.data.data[0].url; res.status(200).json({ success: true, data: imageUrl, }); } catch (error) { if (error.response) { console.log(error.response.status); console.log(error.response.data); } else { console.log(error.message); } res.status(400).json({ success: false, error: 'The image could not be generated', }); } }; module.exports = { generateImage }; |
As you can see in the above code we are making the fetch call to the api. And we are getting the information of api keys from the .env
file and using that we are generating new images and send json response back to the client. Now if you run the node.js
app you will see the below code