Teach you to create a picture generator based on OpenAI and React (support Chinese)

a84f1907021c8cd1492f60574cdc0c4a.png

Created by Midjourney, the future AI robot

Welcome to the world of artificial intelligence applications! In this article, we'll explore the exciting opportunities for creating image generator applications using React and the powerful OpenAI platform. Whether you're a beginner or an experienced developer, you'll learn how to harness the power of machine learning to generate stunning images with just a few lines of code. From building the front-end interface to integrating the OpenAI API, we will walk you through the whole process step by step. So, let's get started and discover how to create an artificial intelligence powered React image generator app using OpenAI!

project settings

Let's build our AI-powered React image generator app by setting up a new React app with Vite. Make sure you have Node.js and Yarn installed on your system, and start executing the following commands:

$ yarn create vite

Next, Vite will start the build process and ask you to enter a project name:

dd1e71aff3c082c2a719edeb590e4335.jpeg

In the next step, Vite will ask you to choose a frame. You can use the arrow keys on your keyboard to select the "React" option and press Enter again. In the end, you need to decide which React project to use. In this article's example, we selected the "JavaScript + SWC" option.

Further reading: What is JavaScript + SWC?

"JavaScript + SWC" is a variant of the React project, where "SWC" refers to a JavaScript compiler. In this configuration, the SWC compiler will be used to compile JavaScript code to improve the performance and execution efficiency of React applications. Compared to other options, such as "TypeScript" or "JavaScript + Babel", using "JavaScript + SWC" can get better performance and faster compilation speed.

ef2a3fc4c46c711609e0a6b9faee5385.jpeg

Change into the newly generated project folder with the following command:

$ cd react-image-gen

Execute the "yarn" command in that folder to make sure all dependencies are downloaded and installed in the project folder:

$ yarn

Additionally, we need to make sure the "openai" package is added to the React project to be able to access the OpenAI API:

$ yarn add openai

Enter the following command to start the development web server:

$ yarn dev

Once the server starts, you should be able to see this default project in your browser:

db9d37302a54ce4f5f58139026117bbd.jpeg

Clean up old code

Let's clean up the default code. Open src/App.jsx and delete everything except the following base App component structure:

import { useState } from 'react'
import './App.css'

function App() {
  return (
    <div className="App">
      <h1>React AI Image Generator</h1>
      <div className="card"></div>
      <p className="read-the-docs">
        Powered by OpenAI
      </p>
    </div>
  )
}

export default App

19566be27457613ddfb1e41d35bf67d5.jpeg

Implementation of the application

Now it's time to start implementing the React application.

First, insert another import statement at the top of App.jsx:

import { Configuration, OpenAIApi } from 'openai'

The code imports two objects, Configuration and OpenAIApi, from the openai package. Next, insert the following code inside the App component:

const [prompt, setPrompt] = useState('')
const [result, setResult] = useState('')
const [loading, setLoading] = useState(false)

The code defines three state variables in the App component using the useState hook.

prompt is a string state variable initially set to the empty string. It is used to store text prompts that will be sent to the OpenAI API to generate images or text.

result is also a string state variable, initially set to the empty string. It is used to store the results returned by the OpenAI API after sending hints.

loading is a boolean state variable initially set to false. It is used to indicate whether a request to the OpenAI API is currently in progress. When loading is set to true, it means that the request is in progress, and when it is set to false, it means that the request has completed or has not started yet.

useState hook is a built-in React hook that allows you to add state to functional components. It returns an array containing the current state value and a function to update the state value. The setPrompt, setResult, and setLoading functions are used to update their respective state variables.

Let's go ahead and add the following code to the App component:

const configuration = new Configuration({
    apiKey: import.meta.env.VITE_OPENAI_API_KEY,
  })

  const openai = new OpenAIApi(configuration);

This code creates two objects, configuration and openai.

configuration is an instance of the Configuration class imported from the openai package. It takes an object as a parameter, which has a property called apiKey. The value of this property is
obtained from the import.meta.env.VITE_OPENAI_API_KEY variable.

VITE_OPENAI_API_KEY contains the API key used to access the OpenAI API. In order to make this environment variable available, you need to create a new file called .env in the root folder of your React project. In that file, you need to set this environment variable to your personal OpenAI API key as follows:

VITE_OPENAI_API_KEY=[INSERT YOUR OPENAI API KEY HERE]

To retrieve your OpenAI API key, you need to create a user account on https://openai.com/ and visit the API keys section in the OpenAI dashboard to create a new API key.

94c2da5bbaa7a82e6e1f9135181bcae9.jpeg

OpenAIApi is also a class imported from the openai package. openai is an instance of this class, which is created by passing a configuration object as an argument.

The Configuration class is used to set the necessary configuration of OpenAI API, such as API key. The OpenAIApi class is used to interact with the OpenAI API, such as sending requests to generate images or text.

Then pass the configuration object as a parameter to the constructor of the OpenAIApi class to create an instance of this class that can be used to interact with the OpenAI API.

Now, let's create a function in the App component to generate the image:

// 定义一个生成图像的异步函数
const generateImage = async () => {
  // 开始请求,设置 loading 为 true
  setLoading(true)

  // 调用 OpenAI API 创建图像,使用 prompt、n 和 size 作为参数
  const response = await openai.createImage({
    prompt: prompt, // 文本提示
    n: 1, // 生成图像的数量
    size: "512x512", // 生成图像的大小
  })

  // 请求结束,设置 loading 为 false
  setLoading(false)

  // 从响应数据中获取图像的 URL,存储到 result 状态变量中
  setResult(response.data.data[0].url)
}

The code defines a function called generateImage, which is an asynchronous function that sends a request to the OpenAI API to generate an image based on prompts provided by the user.

The function first uses the setLoading function to set the loading status variable to true to indicate that the request is in progress. Next, it sends a request to the OpenAI API using the openai.createImage method (method provided by the OpenAIApi class). The request contains hint, n (number of images to generate), and image size. Once the response is received, the function uses the setLoading function to set the loading status variable to false to indicate that the request is complete. It then updates the result state variable with the URL of the generated image using the setResult function. This URL can be used to display an image on the front end. Finally, we need to extend the JSX code returned from the App component to build the user interface:

return (
  <div className="app">
    <h1>React AI Image Generator</h1>

    {/* 如果 loading 状态变量为 true,则显示正在生成图像的提示 */}
    {loading ? (
      <h2>正在生成图像,请稍候!</h2>
    ) : (
      // 否则什么也不显示
      <></>
    )}

    <div className="card">
      {/* 输入文本框 */}
      <textarea
        className="text-input"
        placeholder="输入提示"
        onChange={(e) => setPrompt(e.target.value)}
        row="5"
        cols="50"
      />

      {/* 生成图像按钮 */}
      <button className="button" onClick={generateImage}>
        生成图像
      </button>

      {/* 如果 result 状态变量中有图像的 URL,则显示生成的图像 */}
      {result.length > 0 ? (
        <img className="result-image" src={result} alt="生成的图像" />
      ) : (
        // 否则什么也不显示
        <></>
      )}
    </div>

    <p className="footer">Powered by OpenAI</p>
  </div>
)

This JSX code defines the structure of the components that render the UI of a React application. It returns a div element with class "app". It contains a heading h1 with the text "React AI Image Generator", which is the title of the application. Then it has a ternary operator which checks the value of the loading state variable. If true, display an h2 element with the text "Generating image, please wait!" to indicate that an image generation request is in progress. If false, an empty JSX element <></> is returned.

Inside the div element, it has another div element with class "card". This element contains a textarea element which acts as a text input area with a placeholder "prompt" and an onChange event which calls the setPrompt function and passes the value of the text area as a parameter. It also contains a button element with class "button", which calls the generateImage function when clicked.

Then it has another ternary operator that checks if the length of the result state variable is greater than 0. If true, displays an img element which is the generated image with the src attribute set to the result state variable and has the alt attribute "generated image". If false, an empty JSX element <></> is returned.

This JSX code defines the component's UI, using state variables and functions to control the application's UI and flow.

full source code

Here is the full source code of the React AI Image Generator application:

import { useState } from 'react'
import { Configuration, OpenAIApi } from 'openai'
import './App.css'

function App() {
    // 定义三个 state 变量,分别表示输入框中的提示,生成的结果图片 URL 和加载状态
    const [prompt, setPrompt] = useState('')
    const [result, setResult] = useState('')
    const [loading, setLoading] = useState(false)

    // 创建 Configuration 实例,用于配置 OpenAI API 的 API Key
    const configuration = new Configuration({
        apiKey: import.meta.env.VITE_OPENAI_API_KEY,
    })

    // 创建 OpenAIApi 实例,用于和 OpenAI API 进行交互
    const openai = new OpenAIApi(configuration);

    // 定义生成图片的异步函数
    const generateImage = async () => {
        setLoading(true) // 开始请求,将加载状态设为 true
        // 发送请求并等待响应结果,结果中包含了生成的图片的 URL
        const response = await openai.createImage({
            prompt: prompt, // 提示文本
            n: 1, // 生成图片的数量
            size: "512x512", // 生成图片的大小
        });
        setLoading(false) // 请求结束,将加载状态设为 false
        setResult(response.data.data[0].url) // 将响应结果中的图片 URL 存储到 state 变量 result 中
    };

    // 返回应用程序的 UI
    return (
        <div className="app">
            <h1>ReactAI 图片生成器</h1>
            {loading ? ( // 如果正在加载,则显示“图片生成中...”的提示
                <h2> 正在生成图像,请稍候!</h2>
            ) : (<></>)}
            <div className="card">
        <textarea
            className="text-input"
            placeholder="输入提示词"
            onChange={(e) => setPrompt(e.target.value)} // 当文本框的值改变时,更新 state 变量 prompt
            row="5"
            cols="50"
        />
                <button className="button" onClick={generateImage}>生成图片</button> {/* 点击按钮时,调用异步函数 generateImage */}
                {result.length > 0 ? ( // 如果有生成的图片,则显示图片
                    <img className="result-image" src={result} alt="Generated Image" />
                ) : (
                    <></>
                )}
            </div>
            <p className="footer">
                Powered by OpenAI
            </p>
        </div>
    )
}

export default App

This code is the CSS style code of the application, which is used to define the style and layout of the various elements in the application. (src/App.css: )

/* 根元素的样式 */
#root {
  max-width: 1280px; /* 最大宽度为 1280 像素 */
  margin: 0 auto; /* 自动居中 */
  padding: 2rem; /* 上下左右内边距为 2 个 rems */
  text-align: center; /* 文字居中 */
}

/* 应用程序的样式 */
.app {
  display: flex; /* 设置弹性盒子 */
  flex-direction: column; /* 垂直排列子元素 */
  align-items: center; /* 子元素水平居中 */
}

/* 输入框的样式 */
.text-input {
  height: 50px; /* 高度为 50 像素 */
  width: 100%; /* 宽度为父元素的宽度 */
  margin-bottom: 20px; /* 下边距为 20 像素 */
  border: 2px solid lightgrey; /* 边框为 2 像素的浅灰色 */
  padding: 10px; /* 内边距为 10 像素 */
  font-size: 14px; /* 字体大小为 14 像素 */
  border-radius: 5px; /* 圆角半径为 5 像素 */
}

/* 结果图片的样式 */
.result-image {
  margin-top: 20px; /* 上边距为 20 像素 */
  border: 2px solid lightgray; /* 边框为 2 像素的浅灰色 */
  padding: 10px; /* 内边距为 10 像素 */
  width: 100%; /* 宽度为父元素的宽度 */
}

/* 卡片的样式 */
.card {
  padding: 2em; /* 上下左右内边距为 2 个 em */
  display: flex; /* 设置弹性盒子 */
  flex-direction: column; /* 垂直排列子元素 */
}

/* 底部文字的样式 */
.footer {
  color: #888; /* 文字颜色为浅灰色 */
}

test application

Now it's time to test our application. Visit the application in a browser and you should now be able to see the following UI:

6af8817feaab542aa4cce883f56cf878.png

Please try entering a text prompt describing the image you would like OpenAI to generate. (support Chinese)

bf6159625de116996ceb73ea59b665df.png

Click the "Generate Image" button, it will take a few seconds to generate the image, and you will see the generated image on the web page after the generation is complete

Isn’t it interesting? Although there is a gap with Midjourney, it is not like Baidu, who does not know what will happen to the paid GPT4 interface. I use the free GPT3 interface:

bbee17ed6f3bea3e73d19c662329d2b4.png

Finish

This blog post shows you how to build an AI image generator application in React using the OpenAI API. Through this blog, you learned how to create a visually compelling front-end interface and generate images using the OpenAI API. With this app, you can now generate images on demand and use them for various applications like social media, marketing campaigns and even art projects. I hope this tutorial was helpful and inspired you to experiment with other AI projects. Happy programming!

That’s all for today’s sharing, thank you for reading, I hope it can help you, it’s not easy to create articles, if you like my sharing, don’t forget to like and forward it, so that more people in need can see it, and finally don’t forget to pay attention "Front-end experts", your support will be the biggest motivation for me to share, and I will continue to output more content in the future, so stay tuned.

Original:
https://medium.com/codingthesmartway-com-blog/create-an-ai-powered-react-image-generator-app-using-openai-79b575d6b808

Author: Sebastian

Indirect translation, some self-adapted and added parts, the translation level is limited, it is inevitable that there are omissions, welcome to correct

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/129828160