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+ }
0 commit comments