How to Add Text to Image in Laravel 11

How to Add Text to Image in Laravel 11 – Step-by-Step Guide

Learn How to Add Text to Image in Laravel 11 with this comprehensive step-by-step guide. Follow best practices and code examples for seamless text overlay on images in your Laravel projects.

We will use the Intervention/Image Composer package to add text to image in Laravel. We will install the Intervention/Image-Laravel Composer package to utilize the Intervention/Image library in Laravel. The Intervention/Image library provides several methods like resize, add text, add watermark, blur effect to images.

In this example, we will install the Intervention/Image Composer package. Intervention/Image provides methods to add text to image using the `read()` and `text()` methods. we will define font size, font color and font familly as well. We will create a simple form with the file input field. You can choose an image, and then you will see a preview of the image.

How to Add Text to Image in Laravel 11 – Step-by-Step Guide

Step for How to Add Text to Image in Laravel 11

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel TextToImage

Step 2: Install Intervention Image Package

In the second step, we will install intervention/image-laravel for resizing images. This package allows us to generate thumbnail images for our project. So, first, fire the command below in your CMD or terminal:

composer require intervention/image

Step 3: Create Routes

In this step, we will add routes and a controller file. So first, add the below route in your routes.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');

Step 4: Create Controller File

Now, it is required to create a new ImageController for image upload and add text to image. So, first, run the command below:

php artisan make:controller ImageController

After this command, you can find the ImageController.php file in your app/Http/Controllers directory. Open ImageController.php file and put below code in that file.

Make sure you have created “images” folder in the public folder.

Now, you can download font from here: Click Here. After download create “fonts” folder and put files there.

app/Http/Controllers/ImageController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Intervention\Image\Typography\FontFactory;

  
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('imageUpload');
    }
        
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'image' => ['required'],
        ]);
        
        $image = $request->file('image');
        $imageName = time().'.'.$image->extension();
        $manager = new ImageManager(new Driver());

        $path = public_path('images');
        $img = $manager->read($image->path());
        $img->text('Example form DevScriptSchool.com', 100, 100, function (FontFactory $font) {
            $font->filename(public_path('fonts/LilitaOne-Regular.ttf'));
            $font->color('black');
            $font->size(70);
            $font->stroke('ff5500', 2);
            $font->lineHeight(1.6);
            $font->angle(2);
            $font->wrap(250);
        });

        $img->save($path.'/'.$imageName);
        return back()->with('success', 'You have successfully upload image.')
                     ->with('imageName', $imageName); 
    }
}

Step 5: View File and Create Upload directory

Okay, in this last step, we will create the imageUpload.blade.php file for the photo upload form and manage error messages and also success messages. So first, create the imageUpload.blade.php file and put the code below:

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Add Text to Image in Laravel 11? - ItSolutionStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
        
<body>
<div class="container">
  
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> How to Add Text to Image in Laravel 11? - DevScriptSchool.com</h3>
        <div class="card-body">

            @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
  
            @session('success')
                <div class="alert alert-success alert-block">
                    {{ $value }}
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <strong>Output:</strong>
                        <br/>
                        <img src="/images/{{ Session::get('imageName') }}" width="500px" />
                    </div>
                </div>
            @endif
            
            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
        
                <div class="mb-3">
                    <label class="form-label" for="inputImage">Image:</label>
                    <input 
                        type="file" 
                        name="image" 
                        id="inputImage"
                        class="form-control @error('image') is-invalid @enderror">
        
                    @error('image')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
                </div>
             
            </form>
        </div>
    </div>
</div>
</body>
      
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/image-upload

Leave a Reply