Ever seen those avatars (basically everywhere) that has your initials — mine would be LR; Lasse Rafn — well this package allows you to generate those, in a simple manner.
It’s framework agnostic, which is different from basically everything else I do, you’re welcome.
You just require using composer and you’re good to go!
composer require lasserafn/php-initial-avatar-generator
Rad, and long, package name.. huh? Sorry. I’m not very good with names.
As with installation, usage is quite simple. Generating a image is done by running:
$avatar = new LasseRafn\InitialAvatarGenerator\InitialAvatar();
$image = $avatar->name('Lasse Rafn')->generate();
Thats it! The method will return a instance of Image from Intervention so you can stream, download or even encode the image:
return $image->stream('png', 100);
You can also just pass along the initials, and it will use those. Should you just include a first name, it will use the first two letters of it.
Of cause, passing a name is not the only thing this sweet thing does!
$image = $avatar->name('Albert Magnum')->generate();
// will be 96x96 pixels.
$image = $avatar->size(96)->generate();
// will be red
$image = $avatar->background('#ff0000')->generate();
// will be red
$image = $avatar->color('#ff0000')->generate();
Two fonts are included:
The method automatically appends DIR to it, so the font will be: __DIR__ . '/fonts/OpenSans-Regular.ttf'
// will be Semibold
$image = $avatar->font('/fonts/OpenSans-Semibold.ttf')->generate();
Will use intervention/imagecache to cache the result.
$image = $avatar->cache()->generate(); // 60 minutes
You can simply use ->cache() and it will set cache to 60 minutes, but you can also say ->cache(180) to cache for 180 minutes.
$image = $avatar->name('John Doe Johnson')->length(3)->generate(); // 3 letters = JDJ
$image = $avatar->rounded()->generate();
I recommend that you simply do not enable rounding, as the edges are way too sharp, compared to simply setting border-radius: 100%
on the image (see below)
$image = $avatar->fontSize(0.25)->generate(); // Font will be 25% of image size.
If the Image size is 50px and fontSize is 0.5, the font size will be 25px.
We will not use the ->font() method in this example; as I like the regular one.
return $avatar->name('Lasse Rafn')
->length(2)
->fontSize(0.5)
->size(96) // 48 * 2
->background('#8BC34A')
->color('#fff')
->cache()
->generate()
->stream('png', 100);
Now, using that in a image (sized 48x48 pixels for retina):
<img src="url-for-avatar-generation" width="48" height="48" style="border-radius: 100%" />
Will yield:
Rounded for appearance; the actual avatar is a filled square