Step 1: Install Intervention Image Package to Project
Firstly you have to install the package to your project using the composer command below.
composer require intervention/image
Step 2: Retrieve the Image to be Watermarked
For this example, we'll show you how to retrieve the image and do the processing to a custom route but for your use case, do put this code anywhere necessary (controller or repository class).
<?php Route::get('watermark-image', function (Request $request) { // Option 1: if you are getting the image from the client do get it through the request object $image = $request->file('image'); // Option 2: otherwise you can retrieve it from your storage disk $user_profile = User::first()->profile_picture; // image path e.g user-profile-picture.jpeg $image = \Storage::disk('s3')->get($user_profile); // getting the user profile image form "s3" });
Step 3: Add Watermark to Image
Now that you have the image data already, you can apply the text watermark to the image itself using the Intervention Package "text()" method. This method accepts the text to be placed as the watermark as the first parameter.
<?php Route::get('watermark-image', function () { $user_profile = User::first()->profile_picture; $image = \Storage::disk('s3')->get($user_profile); $interventionInstance = Intervention\Image::make($image) ->text('© hello world. 2021'); // watermark the image using "text()" method Storage::disk('s3')->put($user_profile, $interventionInstance, 'public'); return 'the image has been successfully watermarked'; });
Other Options For Text Watermark
Do note that there are many other options to change the appearance of the watermark and below are the options that you can optionally add if necessary.
<?php // write text at position $interventionInstance->text('The quick brown fox jumps over the lazy dog.', 120, 100); // use callback to define details $interventionInstance->text('foo', 0, 0, function($font) { $font->file('foo/bar.ttf'); $font->size(24); $font->color('#fdf6e3'); $font->align('center'); $font->valign('top'); $font->angle(45); }); // draw transparent text $interventionInstance->text('foo', 0, 0, function($font) { $font->color(array(255, 255, 255, 0.5)); });
If you do find this tutorial to be helpful do make sure to share it with your friends and cheers, happy coding!
Leave a reply