Hello Artisans,
- In today's digital era, images play a vital role in enhancing user experiences across various applications and platforms.
- OpenAI's Image API offers incredible opportunities to harness the power of artificial intelligence and machine learning for image-related tasks. In this tutorial, we'll explore how to integrate OpenAI's Image API into a Laravel application, enabling you to unlock exciting image-based functionalities.
Prerequisites:
To follow this tutorial, you should have a basic understanding of Laravel and its ecosystem. Familiarity with RESTful APIs. Additionally, ensure that you have a working Laravel installation along with composer, the PHP package manager. We are going to use guzzlehttp/guzzle http client for api calls.
Step 1: Obtaining OpenAI API Credentials
Before diving into the integration, we have to obtain OpenAI API credentials by visiting the OpenAI website https://openai.com/ create your account by sign up or log in to your account. Once logged in, navigate to the API section https://platform.openai.com/account/api-keys and create a new API key. Keep the generated key secure, as it will be used in the Laravel application.
Step 2: Install Laravel, breeze and vue using following command
composer create-project laravel/laravel laravel-openai-api
cd laravel-openai-api
composer require laravel/breeze --dev
php artisan breeze:install vue
php artisan migrate
npm install
npm run dev
Step 3: Install Guzzle http client
composer require guzzlehttp/guzzle
Step 4: Add open-ai
api key to your env
file. Now add this variable to services.php
in the config
folder. This is an efficient and reliable way to access env variables from our codebase.
OPENAI_API_KEY=your-api-key-goes-here
services.php
'chatgpt' => env('OPENAI_API_KEY')
Step 5: Create controller and web route
php artisan make:controller ImageGeneratorController
// add these routes in youe web.php file
Route::get('/generate/img', [ImageGeneratorController::class, 'index'])->name('generate.img.index');
Route::post('/generate/img', [ImageGeneratorController::class, 'generateImage'])->name('generate.img');
Step 6: Create ImageGenerator.vue
vue file to create frontend to generate an image, add the below code in your vue file
<script setup>
import InputLabel from "@/Components/InputLabel.vue";
import axios from "axios";
import { ref } from "vue";
import { ArrowPathIcon } from "@heroicons/vue/24/solid";
components: {
InputLabel;
}
const images = ref([]);
const form = {
prompt: "",
n: 1,
size: "1024x1024",
};
const isLoading = ref(false);
const getImg = async () => {
if (images.value.length >= 0) {
images.value = [];
}
isLoading.value = true;
const {
data: { data },
} = await axios.post(route("generate.img"), form);
images.value = data;
if (data) {
isLoading.value = false;
}
};
</script>
<template>
<div class="container mx-auto py-8 px-10">
<p class="text-center text-lg font-bold p-4">
Example of ChatGPT Image Generation
</p>
<div class="w-full max-w-3xl mx-auto">
<form
class="bg-lime-200 shadow-md rounded px-8 pt-6 pb-8 mb-4"
@submit.prevent="getImg"
>
<div class="flex items-center border-b border-lime-600 py-2">
<input
class="appearance-none bg-transparent border-none w-full text-lime-900 mr-3 py-1 px-2 leading-tight focus:outline-none"
type="text"
placeholder="Enter image Description"
aria-label="Image Description"
v-model="form.prompt"
/>
<button
:class="{ 'w-28': isLoading }"
class="inline-flex items-center flex-shrink-0 bg-lime-500 hover:bg-lime-700 border-lime-500 hover:border-lime-700 text-sm border-4 text-white py-1 px-5 rounded"
type="submit"
>
Generate
<ArrowPathIcon
class="ml-3 animate-spin"
v-if="isLoading"
/>
</button>
</div>
</form>
<div
v-if="isLoading"
class="h-2 animate-pulse bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 rounded"
></div>
</div>
<div class="mt-8 w-full max-w-xl mx-auto">
<div v-for="(image, index) in images" :key="index">
<img :src="image.url" alt="no image" height="50" />
</div>
</div>
</div>
</template>
<style>
.showLoader {
margin-left: 20px;
}
</style>
Step 7: Open your ImageGeneratorController.php
controller, add below code
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request as GuzzelHttpRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Http;
use Inertia\Inertia;
class ImageGeneratorController extends Controller
{
public function index()
{
return Inertia::render('ImageGenerator');
}
public function generateImage(Request $request)
{
$client = new Client([
'verify' => false,
// 'verify' => 'C:/php8/cacert.pem',
]);
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' .config('services.chatgpt')
];
$body = json_encode($request->all());
$req = new GuzzelHttpRequest('POST', 'https://api.openai.com/v1/images/generations', $headers, $body);
$res = $client->sendAsync($req)->wait();
return response()->json(json_decode($res->getBody()->getContents()));
}
}
Now run the project and create stunning images.
Staring point of application
The image created from text
Here is the link of my github repository
Thank You, Happy Reading ❤️ 🦄
Top comments (0)