Generate Images from Text Using Hugging Face API in Laravel

How to Generate image from text in Laravel

Generate Images from Text Using Hugging Face API in Laravel


🧠 AI is changing the way we build apps. One exciting thing it can do is generate images from plain text—you type a sentence, and it creates a picture for you! In this blog, we’ll learn how to do that using the Hugging Face API in a Laravel application.

In this article we will ses how to generate image from text using Hugging Face API in Laravel. For example you will provide a text and as an output we will get an image that justifies the text provided. To achieve this we will be using fal-ai/fal-ai/hidream-i1-full Model with Hugging Face API.

📌 What is Hugging Face?

Hugging Face is a platform that provides ready-to-use machine learning models, including NLP (text), image generation, speech, and more. Instead of building your own AI models from scratch, you can use their pre-trained models via API.

🔐 Note: If you haven’t already set up your Hugging Face API key, check out my blog How to get started with Hugging Face: Generating an Access Token for Its API.

🎯 Why Use Text-to-Image?

Imagine you type:
"A cute panda sitting under a tree with sunglasses"

…and you instantly get an AI-generated image matching that. Pretty cool, right? Not only for fun purpose, it can help you in several scenarios as below.

💡Here’s how this can help:

🛒 E-commerce: Generate product mockups on the fly
🎨 Design tools: Let users create custom graphics by typing ideas
🧙‍♂️ Games/Metaverse: Create environments or characters based on text
✍️ Blogs & Marketing: Add unique visuals to your posts
📚 Education: Visualize concepts for better understanding

No need to hire a designer for every small visual. AI helps you create instantly, at a much lower cost.

🔧 How Does It Work in Laravel?

We’ll send a text prompt to Hugging Face using Laravel backend, and it will return an image (in binary). We’ll then show that image in the frontend.

Step 1: Having Hugging Face Access Token

Make sure you have Hugging Face access token stored anywhere in the project, so that we can use it while dealing with Hugging Face API's. In My case i have stored the access token in my .env file. It should look something like this.

hf_Hpxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Step 2: Define Routes

I have created two routes here, one for the UI and another is to process the image and for dealing with Hugging face API.

Route::get('/text-to-image', [HuggingFaceController::class, 'textToImage']);
Route::post('/text-to-image-process', [HuggingFaceController::class, 'textToImageProcess'])->name('text-to-image-classification');

Step 3: HuggingFaceController.php

Now setup your controller as shown below. Feel free to update this according to your needs.

    public function textToImage()
    {
        return view('huggingface.text-to-image');
    }
    public function textToImageProcess(Request $request)
    {
        $url = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev";
        $data = ["inputs" => $request->text];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . env('HUGGINGFACE_TOKEN'),
            'Content-Type' => 'application/json',
        ])->withOptions(['stream' => true])->post($url, $data);

        if ($response->successful()) {
            return response($response->body(), 200)->header('Content-Type', 'image/png');
        }

        return response()->json(['error' => 'Failed to generate image'], 500);
    }

Step 4: text-to-image.blade.php

Next step is to setup your view file to render the image and show results that comes from Hugging Face API. I have used AJAX and Javascript to make the UI look better but you can use them according to your needs.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text To Image</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen p-4">
    <div class="bg-white p-8 rounded-lg shadow-lg w-full max-w-3xl text-center">
        <h1 class="text-3xl font-bold mb-6 text-gray-700">Text to Image Generator</h1>
        
        <form id="textSubmitForm" class="mb-6">
            <input type="text" id="textInput" placeholder="Enter text here..." class="border p-3 rounded-lg w-full mb-4 text-lg">
            <button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-lg font-semibold text-lg">
                Generate Image
            </button>
        </form>
        
        <div id="loading" class="hidden text-blue-500 font-semibold text-lg">Processing...</div>
        
        <div id="result" class="mt-6 hidden">
            <h2 class="text-2xl font-semibold text-gray-700 mb-4">Generated Image:</h2>
            <div class="flex justify-center">
                <img id="generatedImage" class="rounded-lg shadow-md w-full h-auto max-h-[500px] object-contain" src="" alt="Generated Image">
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            $("#textSubmitForm").submit(function(event) {
                event.preventDefault();
                
                var textData = $("#textInput").val();
                if (!textData) {
                    alert("Please enter some text.");
                    return;
                }
                
                $("#loading").removeClass("hidden");
                $("#result").addClass("hidden");
                
                $.ajax({
                    url: "{{ route('text-to-image-classification') }}", 
                    type: "POST",
                    data: JSON.stringify({ text: textData }),
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    contentType: "application/json",
                    xhrFields: {
                        responseType: 'blob' // Expecting a binary image response
                    },
                    success: function(blob) {
                        const imageUrl = URL.createObjectURL(blob);
                        $("#generatedImage").attr("src", imageUrl);
                        $("#result").removeClass("hidden");
                    },
                    error: function() {
                        alert("Error generating image.");
                    },
                    complete: function() {
                        $("#loading").addClass("hidden");
                    }
                });
            });
        });
    </script>
</body>
</html>

Output: 

Generate Images from Text Using Hugging Face API in Laravel


🔚 Conclusion: 

Using Hugging Face with Laravel, you can easily build a smart image generation tool with just a few lines of code. It’s powerful, flexible, and opens up creative possibilities for your apps.

Give it a try, and turn your words into art! 🎨🖌️


Previous Post Next Post

Contact Form