IT & Programming

Generate image from text with Laravel Intervention

There are many text to image generation articles on internet using intervention image package but they are all buggy. Please follow the easy steps below to create an image from string.

Intervention Installation

First step is to install intervention image package. You can either go to image.intervention.io for more installation options or simply run this command.

composer require intervention/image

Class & Function

use Intervention\Image\Facades\Image;

class ImageClass
{
    public static function generate()
    {

        $path = public_path('assets/images/black.png');

        $img = Image::make($path);

        $img->text('Cake' 300, 200, function ($font) {
            $font->file(public_path('assets/fonts/arial.ttf'));
            $font->size(54);
            $font->color('#ffffff');
            $font->align('center');
            $font->valign('middle');
            $font->angle(0);
        });

        $img->save(public_path('pictures/cake.png'));
    }

}

Explanation (Must Read)

$path = public_path('assets/images/black.png');

You must first create a default base image with a background color in paint or in any other image editor. The text will be printed on this image. In this example, i created an image in paint with black background and named it black.png. The resolution of the image was 600 x 400.

$img->text('Cake' 300, 200, function ($font) {

'Cake' is the text that will be printed on the image. 300 is margin from left and 200 is margin from top.

$font->file(public_path('assets/fonts/arial.ttf'));

You must provide the path of font file otherwise, you will see an error. In this example I just searched "arial.ttf" in google, downloaded it to fonts directory of my project and set the path in function.

$img->save(public_path('pictures/cake.png'));

Set the path where new image will be stored with your desired file name.

Calling The Function

ImageClass::generate();

Output

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *