Image Generation using Open AI Image Creation API in Angular

Hello everyone, Here we will discuss how we can use Image Creation OpenAI API to create/generate the images and show images directly on the UI. For that, I'm using Angular.

What is Image Creation OpenAI API?

How can we generate or manipulate images with OpenAI DALL·E models

This Images API provides three methods for interacting with images:

  1. Creating images from scratch based on a text prompt passed by the user
  2. Creating edits of an existing image based on a new text prompt
  3. Creating variations of an existing image

In this article, we are only creating images based on user-provided input.

Find more details here in this link Image Creation OpenAI

Generate Images using OpenAI API

Step 1. Create an OpenAI account

Go to the OpenAI (https://openai.com/) website and click on the Try ChatGPT button to create an account and sign up if you are new. Otherwise, click on the login button.

Image Generation using Open AI Image Creation API in Angular

Step 2. Get the OpenAI API key

Login into your OpenAI account, click on the profile right-hand tab, then click View API Keys, highlighted with a yellow marker below the screenshot. 

Once you click on View API Keys, you need to Create a new secret key if you don't have one previously. Once you click on it, an API key will generate in the Popup window, and you can copy it for using it in the application where we use this API key.

In the screenshot below, you can find your generated API keys as I've already generated it shows me like this.

Image Generation using Open AI Image Creation API in Angular

Step 3. Create a new Angular application

ng new openaidemo

We are using the Node.js library, which you can install by running the following command.

Step 4. Install the OpenAI npm package

npm install openai

Step 5. Install the ngx-spinner npm package (optional)

npm install ngx-spinner

Install this package to show some interactive loader while fetching data from the server and rendering it to UI. For further info, you can follow this npm package link. 

  1. NPM ngx-spinner link 
  2. Github Link for ngx-spinner package

Note: I'm using the Tailwind CSS framework on the UI side. You can follow the below link to set it up in your angular project. 

Step 6. Add configuration code of OpenAI in app.component.ts file

import { OpenAIApi, Configuration } from "openai"; 

configuration = new Configuration({
    apiKey: "Enter your OpenAI API Key Over here",
});
openai = new OpenAIApi(this.configuration);

contentData: any[] = []; //store API response from OpenAI over here and render it on UI.

this.response = await this.openai.createImage({
      prompt: "Dog on a boat",
      n: 2,
      size: '512x512'
    }).then(x => {     
console.log('api response from open ai ',x)
       this.contentData = x.data.data;
});

Step 7. Add the FormControl to get the user-entered value.

Note: Here, I'm using the Reactive Form 

editableFiled = new FormControl('')

Step 7. The code for app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { FormControl, UntypedFormControl } from '@angular/forms';
import { NgxSpinnerService } from 'ngx-spinner';
import { OpenAIApi, Configuration } from "openai";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'ngOpenAIDemo';
  contentData: any[] = [];
  editableFiled = new FormControl('')
  configuration = new Configuration({
    apiKey: "Enter your OpenAI API Key Over here",
  });

  openai = new OpenAIApi(this.configuration);
  response: any;

  constructor(private spinner: NgxSpinnerService) {

  }

  ngOnInit(): void {
   
  }

  public async openAIResponse(prompt: any) {
    this.spinner.show();
    this.response = await this.openai.createImage({
      prompt: prompt, //user entered input text will store here.
      n: 2, //number of images that are we expecting from OpenAI API.
      size: '512x512' //size of image that are we expecting from OpenAI API.
    }).then(x => {
      this.spinner.hide();
      this.contentData = x.data.data;
      console.log('x: ', x.data);
      if (this.editableFiled.value) {
        this.editableFiled.reset();
      }
    }).catch(y => {
      console.log('y: ', y);

    });
  }
  callOpenAI() {
    if (this.contentData.length > 0) {
      this.contentData = [];
    }
    this.openAIResponse(this.editableFiled.value); //getting the userinput value and pass to the function
  }
}

Step 8. The code for the app.component.html file.

<ngx-spinner bdColor="rgba(51,51,51,0.8)" size="large" color="#fff" type="ball-scale-multiple">
</ngx-spinner>

<p class="text-center text-black font-mono text-lg font-bold mt-6">Image Creation using OpenAI</p>


<div class="stretch mx-2 flex flex-row gap-3 pt-2 last:mb-2 md:last:mb-6 lg:mx-auto lg:max-w-3xl lg:pt-6">
  <div class="relative flex h-full flex-1 md:flex-col">
    <div
      class="flex flex-col w-full py-2 flex-grow md:py-3 md:pl-4 relative border border-black/10 bg-white dark:border-gray-900/50 dark:text-white dark:bg-gray-700 rounded-md shadow-[0_0_10px_rgba(0,0,0,0.10)] dark:shadow-[0_0_15px_rgba(0,0,0,0.10)]">
      <textarea (keyup.enter)="callOpenAI()" [formControl]="editableFiled" tabindex="0"
        style="max-height: 200px; height: 24px; overflow-y: hidden;" rows="1"
        class="m-0 w-full resize-none border-0 bg-transparent p-0 pl-2 pr-7 focus:ring-0 focus-visible:ring-0 dark:bg-transparent md:pl-0"></textarea>
      <button (click)="callOpenAI()"
        class="absolute p-1 rounded-md text-gray-500 bottom-1.5 right-1 md:bottom-2.5 md:right-2 hover:bg-gray-100 dark:hover:text-gray-400 dark:hover:bg-gray-900 disabled:hover:bg-transparent dark:disabled:hover:bg-transparent"><svg
          stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round"
          stroke-linejoin="round" class="h-4 w-4 mr-1" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
          <line x1="22" y1="2" x2="11" y2="13"></line>
          <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
        </svg></button>
    </div>
  </div>
</div>

<p>&nbsp;</p>

<p *ngIf="contentData?.length" class="text-center text-black font-mono text-lg font-bold mt-6">Result</p>

<div class="flex flex-wrap">
  <img class="w-1/2" *ngFor="let img of contentData" [src]="img?.url">
</div>

Step 8. After adding code in ts and HTML file, below is the output.

When you run your Angular 15 application, you will see UI like the one below.

Image Generation using Open AI Image Creation API in Angular

Step 9. Enter Search Term.

e.g., White Cat playing with ball

Image Generation using Open AI Image Creation API in Angular

Step 10. Output from OpenAI.

Image Generation using Open AI Image Creation API in Angular

This is how we can integrate the Image Creation OpenAI API with our angular application.

Final Output

Image Generation using Open AI Image Creation API in Angular

 

Thanks for reading the article.

HAPPY CODING !!!!!


Similar Articles