Skip to content

Commit 43ba9c4

Browse files
committed
Initial upload
0 parents  commit 43ba9c4

File tree

5 files changed

+271
-0
lines changed

5 files changed

+271
-0
lines changed

composer.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "lasserafn/php-initial-avatar-generator",
3+
"description": "A package to generate avatars with initials for PHP",
4+
"type": "library",
5+
"license": "MIT",
6+
"authors": [
7+
{
8+
"name": "Lasse Rafn",
9+
"email": "[email protected]"
10+
}
11+
],
12+
"require": {
13+
"intervention/image": "^2.3"
14+
}
15+
}

composer.lock

Lines changed: 189 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/InitialAvatar.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php namespace LasseRafn\InitialAvatarGenerator;
2+
3+
use Intervention\Image\Image;
4+
5+
class InitialAvatar
6+
{
7+
/** @var Image */
8+
private $image;
9+
10+
public function __construct()
11+
{
12+
$this->image = new Image();
13+
}
14+
15+
/**
16+
* @param $nameOrInitials
17+
* @param string $bgColor
18+
* @param string $fontColor
19+
* @param int $size
20+
* @param string $font
21+
*
22+
* @return Image
23+
*/
24+
public function generate( $nameOrInitials, $bgColor = '#000', $fontColor = '#fff', $size = 48, $font = 'OpenSans-Regular' )
25+
{
26+
$img = $this->image->canvas( $size, $size, $bgColor );
27+
28+
$img->text( $this->generateInitials( $nameOrInitials ), 0, 0, function ( $font ) use ( $fontColor, $size, $font )
29+
{
30+
$font->file( "fonts/{$font}.ttf" );
31+
$font->size( $size * 0.75 );
32+
$font->color( $fontColor );
33+
$font->align( 'center' );
34+
$font->valign( 'center' );
35+
} );
36+
37+
return $img;
38+
}
39+
40+
/**
41+
* Generate a two-letter initial from a name,
42+
* and if no name, assume its already initials.
43+
* For safety, we limit it to two characters,
44+
* in case its a single, but long, name.
45+
*
46+
* @param string $nameOrInitials
47+
*
48+
* @return string
49+
*/
50+
private function generateInitials( $nameOrInitials = 'John Doe' )
51+
{
52+
$nameOrInitials = strtoupper( trim( $nameOrInitials ) );
53+
54+
$names = explode( $nameOrInitials, ' ' );
55+
if ( count( $names ) > 1 )
56+
{
57+
$firstNameLetter = substr( $names[0], 0, 1 );
58+
$lastNameLetter = substr( $names[ count( $names ) - 1 ], 0, 1 );
59+
60+
$nameOrInitials = "{$firstNameLetter}{$lastNameLetter}";
61+
}
62+
63+
$nameOrInitials = substr( $nameOrInitials, 0, 2 );
64+
65+
return $nameOrInitials;
66+
}
67+
}

src/fonts/OpenSans-Regular.ttf

212 KB
Binary file not shown.

src/fonts/OpenSans-Semibold.ttf

216 KB
Binary file not shown.

0 commit comments

Comments
 (0)