How to Generate image from text 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:
🔧 How Does It Work in Laravel?
Step 1: Having Hugging Face Access Token
hf_Hpxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Step 2: Define Routes
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
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
<!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>