Search code examples
laravelintervention

Generate image having text with user's First Name and Last Name initials


I want every user to have a default profile image when they register. This image will have initial letter of their First Name and Last Name.

I made a plain image with a single color, I then tried to write text on it using Intervention Image. It works, but font size is too small I can't increase it. I don't know what's the max font size in Intervention, as documentation says nothing about it. I also tried with different font, put the font in a font folder and I refer it in $font->file('font/Poppins.ttf'). It throws an error 'Undefined Offset'.

RegisterController.php

protected function create(array $data)
{
    $img = Image::make('storage/avatars/1.jpg');
    $img->text('HW', 125, 80, function ($font) {
        $font->file('font/Poppins.ttf');
        $font->size(40);
        $font->color('#fdf6e3');
        $font->align('center');
        $font->angle(45);
    });
    $filename = time().'.'.'jpg';
    $img->resize(150, 150)->save('storage/avatars/'.$filename);

    return User::create([
        'firstname' => $data['firstname'],
        'lastname' => $data['lastname'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'avatar' => $filename,
    ]);
}

I have a default image which has only red color as background. Whenever a person register he must have this image as default profile picture with his First Name and Last Name's initial letters on it.


Solution

  • You are not giving the correct path to the font.ttf file

    change this

    $font->file('font/Poppins.ttf');
    

    to this

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