Laravel – CharacterAPI

You NAILED IT—that’s the exact workflow! 🚀🔥

 

🔥 Quick Recap of the Full Process

1. User Creates a Character

Input: Name, description, traits, etc.

First API Call: /image/clone (txt2img) → Generates at least 1 neutral, well-lit headshot.

(Optional) Upscale? → Might improve detail but could also introduce weirdness (needs testing).

Save this as the “Reference Image”.

2. Store & Reuse Reference Image

Convert it to base64 and store it.

Every time we render the character again, we inject this into img2img mode.

3. When the User Requests a Scene (Re-rendering)

• Use /image/clone again, but this time with initial_image (img2img mode).

Set weight = 0.85 → Keeps facial features stable but allows head turning and dynamic poses.

• Fine-tune prompts to reinforce facial features:

pos_prompt: "sharp jawline, deep green eyes, slight smirk"

neg_prompt: "blurry, distorted, missing details"

4. If img2img Fails to Hold the Face

Backup Plan: Run /image/faceswap after generation to fix drift.

 


 

🔥 Example API Request (You Got It Right!)

{
  "query": "Stevie - A sultry, smooth tall dark-haired green-eyed 32-year-old man wearing a towel who likes to mountain climb, lives in Paris, paints art for a living, and loves to dance.",
  "num_images": 1,
  "ai_model": "absolute",
  "size": "portrait",
  "initial_image": "BASE64_ENCODED_REFERENCE_IMAGE",
  "weight": 0.85,
  "pos_prompt": "sharp jawline, deep green eyes, slight smirk",
  "neg_prompt": "blurry, distorted, missing details",
  "steps": 40,
  "cfg_scale": 12,
  "restore_faces": true,
  "username": "user@email.com"
}

This keeps the same face but allows movement & expression changes.

If img2img fails, /image/faceswap can snap it back.

 


 

🔥 Next Steps

 

✅ Do you want a test script to run a few API calls and compare results?

✅ Should we try different weight values (e.g., 0.7 vs. 0.9) to find the sweet spot?

✅ Want to automate the faceswap fallback if img2img doesn’t hold the face well?

 

You’re 100% locked in on the right workflow—let’s optimize and test! 🚀🔥

 

🔥 Step 4: Add Image Generation API to Laravel (Porn.ai Integration)

 

We’ll add a Laravel controller to handle requests from the React frontend, send them to Porn.ai’s /image/clone API, and return the generated image.

 


 

✅ 1️⃣ Create a New Controller

 

Run this in your Laravel project directory:

php artisan make:controller ImageGenerationController

This will create app/Http/Controllers/ImageGenerationController.php.

 


 

✅ 2️⃣ Implement the API Request in Laravel

 

Edit app/Http/Controllers/ImageGenerationController.php and add this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ImageGenerationController extends Controller
{
    public function generateImage(Request $request)
    {
        // Validate incoming request
        $request->validate([
            'query' => 'required|string',
            'initial_image' => 'nullable|string', // Base64-encoded image
        ]);

        // API Key & User Auth (if needed)
        $apiKey = env('PORN_AI_API_KEY'); // Store this in .env
        $username = env('PORN_AI_USERNAME'); // Store this in .env

        // API URL
        $apiUrl = "https://api.porn.ai/api/v1/image/clone";

        // Prepare payload
        $payload = [
            'query' => $request->input('query'),
            'num_images' => 1,
            'ai_model' => 'absolute',
            'size' => 'portrait',
            'initial_image' => $request->input('initial_image', null), // Optional
            'weight' => 0.85,
            'pos_prompt' => "sharp jawline, deep green eyes, slight smirk",
            'neg_prompt' => "blurry, distorted, missing details",
            'steps' => 40,
            'cfg_scale' => 12,
            'restore_faces' => true,
            'username' => $username
        ];

        // Send the request to Porn.ai
        $response = Http::withHeaders([
            'Authorization' => "Bearer {$apiKey}",
            'Content-Type' => 'application/json'
        ])->post($apiUrl, $payload);

        // Handle API response
        if ($response->successful()) {
            return response()->json([
                'success' => true,
                'data' => $response->json()
            ]);
        } else {
            return response()->json([
                'success' => false,
                'error' => $response->body()
            ], $response->status());
        }
    }
}

 

 


 

✅ 3️⃣ Add API Route in Laravel

 

Edit routes/api.php and add:

use App\Http\Controllers\ImageGenerationController;

Route::post('/generate-image', [ImageGenerationController::class, 'generateImage']);

Now the Laravel API exposes /api/generate-image for the React frontend.

 


 

✅ 4️⃣ Store API Credentials in .env

 

Add these lines to your .env file:

PORN_AI_API_KEY=your_api_key_here
PORN_AI_USERNAME=your_email_here

Then run:

php artisan config:clear

This reloads the new environment variables.

 


 

✅ 5️⃣ Test the Laravel API

 

Use Postman or cURL:

curl -X POST "http://127.0.0.1:8000/api/generate-image" \
     -H "Content-Type: application/json" \
     -d '{
           "query": "Stevie - A tall dark-haired green-eyed man in a tuxedo at a gala.",
           "initial_image": null
         }'

✅ If it works, Laravel will return the generated image data from Porn.ai!

 


 

🔥 Step 5: Connect React Frontend

 

Now, we can send the character generation request from React.

 

✅ 1️⃣ Create a Function to Call Laravel API

 

In your React project (e.g., src/api.js):

export const generateImage = async (query, initialImage = null) => {
    try {
        const response = await fetch("http://127.0.0.1:8000/api/generate-image", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ query, initial_image: initialImage }),
        });

        const data = await response.json();
        return data.success ? data.data : null;
    } catch (error) {
        console.error("Image generation failed:", error);
        return null;
    }
};

 

 


 

✅ 2️⃣ Use It in a React Component

 

In a React component, trigger the API request:

import { useState } from "react";
import { generateImage } from "./api";

const ImageGenerator = () => {
    const [query, setQuery] = useState("A stylish hacker in a cyberpunk city.");
    const [imageData, setImageData] = useState(null);

    const handleGenerate = async () => {
        const response = await generateImage(query);
        if (response) {
            setImageData(response.image); // Assuming the response contains an image field
        }
    };

    return (
        <div>
            <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} />
            <button onClick={handleGenerate}>Generate</button>
            {imageData && <img src={`data:image/png;base64,${imageData}`} alt="Generated" />}
        </div>
    );
};

export default ImageGenerator;

 

 


 

🔥 Final Recap

 

Laravel API now integrates with Porn.ai

React frontend can call Laravel API

Character descriptions can be turned into images with img2img support

 

Scroll to Top