Laravel 12 - Add Watermarks to Images with Intervention Image.

Touseef Afridi
16 Jan 26

Laravel 12 - Add Watermarks to Images with Intervention Image.

In this tutorial, learn how to add watermarks to images in Laravel 12 using the Intervention Image package. Follow step-by-step instructions to upload images, apply text watermarks, and download files easily.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through adding a watermark to images uploaded through a Laravel 12 application using the Intervention Image package. You’ll create a fresh Laravel project (or use an existing one), install and configure the package, add the Arial font to the public directory, and build an ImageController to handle uploads, validate files, and apply customizable watermarks. Routes are set up for the home page and image processing, and the welcome.blade.php view is updated with a clean, dark-themed, responsive form, allowing users to upload an image and automatically download a watermarked version. This provides a simple and effective way to integrate watermark functionality into any Laravel project.

Step # 1 : Initialize a Laravel 12 Project or Use an Existing Project.

To begin, you can either start a fresh Laravel 12 project or continue working with an existing codebase. If you have the Laravel Installer set up globally, creating a new project is quick and easy, simply run the following command.
laravel new watermark
If you prefer using Composer directly, you can achieve the same result with the following command.
composer create-project laravel/laravel --prefer-dist watermark
This command downloads the latest Laravel 12 release along with all required dependencies into a new watermark directory. When using the Laravel Installer, you’ll be prompted to make a few configuration choices during setup.
  • Would you like to install the starter kit? Select None.
  • Select the testing framework. Choose Pest.
  • Select the database for your application. Choose Mysql.
  • Run the default database migration? Select Yes.
  • Finally, allow it to run npm install and npm run build so your frontend dependencies are installed and compiled.

Once the process finishes, you’ll have a clean Laravel 12 application named watermark, fully configured with Pest for testing, MySQL as the database, and the default migrations already applied, ready for development right out of the box.

Step # 2 : Navigate to the Project Directory.

With the project created, open your terminal (for example, Git Bash or Command Prompt) and move into the root directory of your Laravel application.
cd c:xampp/htdocs/watermark
Being inside the project folder allows you to run Artisan commands, install packages, and manage your Laravel 12 application efficiently.

Step # 3 : Install the Intervention Image Package.

To handle image processing tasks such as resizing, cropping, or adding watermarks, you’ll need the Intervention Image package. Install it using Composer with the following command.
composer require intervention/image-Laravel
This installs the Intervention Image library with Laravel support, giving you a simple API for image manipulation. Make sure to run it from your project’s root so Composer can register it properly.

Step # 4 : Publish the Intervention Image Configuration.

Next, publish the configuration file for the Intervention Image package by running.
php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"
Publishing the configuration adds an image.php file to your project’s config directory. From here, you can adjust settings such as the image driver, selecting GD or Imagick based on your environment.

Step 5: Add the Arial Font to the Public Folder.

First, create a fonts folder inside your project’s public directory.
public/fonts
Then, copy the Arial font into this folder.
  1. Windows: Locate it at C:\Windows\Fonts\arial and paste it into public/fonts.
  2. macOS: Find it at /Library/Fonts/Arial.ttf or /System/Library/Fonts/Arial.ttf and copy it to public/fonts.

Adding the Arial font lets you customize the watermark text size easily. For this tutorial, we’ll stick with system fonts to keep things simple, but you can always download and use other fonts if you want a different style.

Step # 6 : Create a Controller for Image Watermarking.

Next, generate a controller to handle image uploads and apply watermarks.
php artisan make:controller ImageController
Once created, open ImageController.php and replace its content with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\Laravel\Facades\Image;
class ImageController extends Controller
{
    public function addWatermark(Request $request)
    {
        // Validate the uploaded image
        $request->validate([
            'image' => 'required|image|mimes:jpg,jpeg,png|max:2048',
        ]);
        // Open the uploaded image
        $image = Image::read($request->file('image')->getPathname());
        // Add a text watermark using the Arial font from public/fonts, adjust font size, set font color white, align text to the right, align text to the bottom, use Arial font
        $image->text('Code Shortcut', $image->width() - 20, $image->height() - 100, function ($font) {
            $font->size(25);
            $font->color('ffffff');
            $font->align('right');
            $font->valign('bottom');
            $font->filename(public_path('fonts/arial.ttf'));
        });
        // Create a filename for the watermarked image
        $filename = 'watermarked_' . $request->file('image')->getClientOriginalName();
        // Return the image as a downloadable file
        return response($image->encode())
            ->header('Content-Type', $request->file('image')->getMimeType())
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
    }
}
The addWatermark method validates the uploaded image to ensure it’s a JPG, JPEG, or PNG file, applies a text watermark using the Arial font stored in the public/fonts folder, and returns the watermarked image as a downloadable file.

Step # 7 : Set Up Routes for Watermarking.

First, import the ImageController at the top of your routes/web.php file.
use App\Http\Controllers\ImageController;
Then, define routes for the home page and the watermark process.
// Returns the welcome page with the image upload form
Route::get('/', function () {
    return view('welcome');
});
// Processes the uploaded image and returns a watermarked version
Route::post('/add-watermark', [ImageController::class, 'addWatermark']);
The GET route displays the welcome view as the home page, while the POST route handles image uploads and applies the watermark using the addWatermark method.

Step # 8 : Update the Welcome View.

Now, update the home page to include a form for uploading images and applying watermarks. Open resources/views/welcome.blade.php and replace its content with the following.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 12 - Code Shortcut Watermark</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 flex items-center justify-center min-h-screen">
    <div class="bg-gray-800 shadow-2xl rounded-2xl w-full max-w-3xl p-10">
        <h1 class="text-3xl font-bold text-center mb-8 text-white">
            Code Shortcut - Add Watermark
        </h1>
        <!-- Image Upload Form -->
        <form action="{{ url('/add-watermark') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
            @csrf
            <div>
                <label for="image" class="block text-gray-300 font-medium mb-2">Select an image</label>
                <input type="file" name="image" id="image" accept="image/png, image/jpeg" required
                class="w-full px-4 py-3 rounded-lg border border-gray-600 bg-gray-700 text-white
                focus:outline-none focus:ring-2 focus:ring-white hover:border-gray-500">
            </div>
            <!-- Submit Button -->
            <button type="submit"
            class="w-full bg-green-500 text-white py-3 rounded-lg hover:bg-green-600
            focus:outline-none focus:ring-2 focus:ring-green-400 transition-colors duration-200">
            Add Watermark
        </button>
    </form>
</div>
</body>
</html>
This view provides a clean, responsive interface for uploading images. Using Tailwind CSS, the form is styled to be visually appealing and user-friendly. When an image is submitted, it’s sent via POST to the /add-watermark route, where it will be processed and watermarked.

Step # 9 : Test the Watermark Functionality.

Now it’s time to see your watermark feature in action. Start the Laravel development server with.
php artisan serve
This launches Laravel’s built-in development server. Open your browser and go to: http://127.0.0.1:8000. You should see the image upload form on the home page.

Choose an image, click Add Watermark, and the app will process it. A watermarked version of your image will be downloaded automatically.




You can also tweak the font size, color, or alignment in ImageController to adjust the watermark to your preference.

Conclusion

By following this guide, you have successfully added image watermarking to a Laravel 12 application using the Intervention Image package. Users can upload images, apply a customizable text watermark, and download the processed file with ease. This setup provides a simple and flexible foundation that can be extended for more advanced image manipulation or branding needs.
For more details, refer to the official Intervention Image documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering