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.
Thank you to all our backers! 🙏 [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
There's also a api you can use: https://ui-avatars.com
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.
To display the image generated by the InitialAvatarGenerator library directly on a webpage, you can utilize PHP headers to output the image as a stream or generate a temporary file and display it using an <img>
tag.
To output the image as a stream, you can create a separate PHP endpoint (like avatar.php) that generates the avatar image and streams it as a PNG. Then, you use the URL of this endpoint as the src of an <img>
tag on your webpage.
An example endpoint file (avatar.php) is below:
<?php
require 'vendor/autoload.php';
use LasseRafn\InitialAvatarGenerator\InitialAvatar;
header('Content-Type: image/png'); // Set the content type to PNG
$avatar = new InitialAvatar();
$name = isset($_GET['name']) ? $_GET['name'] : 'Default User';
// Generate the image
$image = $avatar->name($name)->generate();
// Stream the image directly to the output
echo $image->stream('png', 100);
exit;
In the HTML file, you can reference the snippet below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Avatar Example</title>
</head>
<body>
<h1>User Avatar</h1>
<!-- Use the PHP endpoint as the image source -->
<img src="avatar.php?name=John Doe" alt="Avatar for John Doe" width="100" height="100">
<img src="avatar.php?name=Jane Smith" alt="Avatar for Jane Smith" width="100" height="100">
</body>
</html>
$avatar = new LasseRafn\InitialAvatarGenerator\InitialAvatar();
echo $avatar->name('Lasse Rafn')->generateSvg()->toXMLString(); // returns SVG XML string
Of cause, passing a name is not the only thing this sweet thing does!
$image = $avatar->name('Albert Magnum')->generate();
Will detect language script (using lasserafn/php-string-script-language) and use a font that supports it.
$image = $avatar->autoFont()->generate();
// will be 96 pixels wide.
$image = $avatar->width(96)->generate();
// will be 96 pixels tall.
$image = $avatar->height(96)->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();
// Will choose a background color based on `name` and a contrasting font color. The color for a specific name will always be the same.
$image = $avatar->autoColor()->generate();
Two fonts with two variants are included:
- /fonts/OpenSans-Regular.ttf
- /fonts/OpenSans-Semibold.ttf
- /fonts/NotoSans-Bold.ttf
- /fonts/NotoSans-Regular.ttf
The method will look for the font, if none found it will append __DIR__
and try again, and if not it will default to the first GD Internal Font.
If you input an integer between 1 and 5, it will use a GD Internal font as per that number.
// will be Semibold
$image = $avatar->font('/fonts/OpenSans-Semibold.ttf')->generate();
$image = $avatar->fontName('Arial, Helvetica, sans-serif')->generate();
$image = $avatar->name('John Doe Johnson')->length(3)->generate(); // 3 letters = JDJ
$image = $avatar->gd()->generate(); // Uses GD driver
$image = $avatar->imagick()->generate(); // Uses Imagick driver
$image = $avatar->rounded()->generate();
Makes rounding smoother with a resizing hack. Could be slower.
$image = $avatar->rounded()->smooth()->generate();
If you are going to use rounded()
, you want to use smooth()
to avoid pixelated edges. Disabled by default because it COULD be slower.
I would recommend just rounding with CSS.
$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')
->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
The package supports FontAwesome (v5) and already distributes the free version as otf
format (see /fonts
folder).
However, when using FontAwesome you may want to display one specific icon instead of the user's initials. This package, therefore, provides a handy glyph($code)
method to be used along with FontAwesome.
First, you need to "find" the respective unicode for the glyph you want to insert. For example, you may want to display a typical "user" icon (unicode: f007
). The unicode is located near the name of the icon (e.g., see here the user icon as an example here: https://fontawesome.com/icons/user ).
An example for rendering a red avatar with a white "user" glyph would look like this:
// note that we
// 1) use glyph() instead of name
// 2) change the font to FontAwesome!
return $avatar->glyph('f007')
->font('/fonts/FontAwesome5Free-Regular-400.otf')
->color('#fff')
->background('#ff0000')
->generate()
->stream('png', 100);
- PHP +7.0
- Fileinfo Extension (from intervention/image)
Some letters are not supported by the default font files, so I added some fonts to add support. You must use autoFont()
to enable this feature. Supported are:
- Arabic
- Armenian
- Bengali
- Georgian
- Hebrew
- Mongolian
- Chinese
- Thai
- Tibetan
Open Source is best when supported by a community. Any size of contribution is very appreciated.
- GD Library (>=2.0)
- Imagick PHP extension (>=6.5.7)
php-initial-avatar-generator's People
Forkers
sybri firestorm-developments dvmoomoodv hadryan johannesschobel man4toman birkof nerandell thatleeguy lluprisinglll mdnbras huseyinaslim dbabaioff xandy3br resthinkphp roro6969 peter279k ncou dael smoqadam soldierm sreenivas74 etdte cloudmanic vishnurnair93 brewdotcom aharen arunlodhi clevertonh dyanakiev 6px abbasogaji rodrigojt tossina phyozawtun doc22940 jimmea yakatz madeval psohm zahedkamal87 seyyedhesammirebrahimi blackmunk hamiidev ogua 3d-i faramarz91 princewaleed77 tmauzet lionrajkumar pobegov allenjb lesuisse dylangd lucliscio nunoarmando unlooped thecoderraman rahulalam31 gifsde zezo-ai mbenjamins tomstory9 manzadey iammutevu rayanroubio yuntong-zhang-sonarsource charescapephp-initial-avatar-generator's Issues
No way to use Imagick as driver?
Hi, from the README:
Supported Image Libraries (from intervention/image)
GD Library (>=2.0)
Imagick PHP extension (>=6.5.7)
But there's no way to specify to use Imagick? It uses GD by default, because that's Intervention's default.
As a solution I think it would be a good option to allow an user to inject their own Intervention\Image\ImageManager
+ be able to set one as a default (via a static method call).
Another thing: I wanted to extend your class, but that's next to impossible due to all the private members. Perhaps you can consider using protected
visibility (wherever possible)?
Cheers ;-)
[FEAT] Emoji/emoticon support
Document `keepCase`
Initials are not centered
Hi,
The generated avatar does not center the initials. This can be visible here for example:
Thanks!
Just wanted to say thanks for this awesome package, works great! :)
Deprecation Notice: Dynamic property creation in InitialAvatar.php with php 8.2
Hello,
I've been using your PHP Initial Avatar Generator library and it has been very helpful. However, I've encountered a deprecation notice with a recent version of PHP. Here's the notice:
Deprecated: Creation of dynamic property LasseRafn\InitialAvatarGenerator\InitialAvatar::$translato is deprecated in /srv/api/vendor/lasserafn/php-initial-avatar-generator/src/InitialAvatar.php on line 571
Would it be possible to update the code to avoid the use of dynamic properties and thus resolve this deprecation notice?
Thanks for your attention to this matter. I appreciate your work on this library and look forward to your response.
generate random color
Hi Lasse, thank you for this pacakge.
Lately, I used this package for my project. I needed to generate a random color for each user. here is my commit if you find it useful let me know to send you a PR.
Thanks
[Regression] SVGs not resizing in IE11
We generate SVG avatars with a single size in the backend, and then use width
and height
attributes of the img
tag to size them as-needed on the frontend. On the latest release, this works fine in all oses/browsers except for Internet Explorer 11.
When we downgrade to 4.1.1
, they look (somewhat) as expected in IE 11
To be clear, they don't look great in IE 11, but at least they're readable 😂
We are okay to stay on version 4.1.1
for the time being, as our use-case doesn't expose the Firefox bug that was fixed in 4.1.2
. But, since our team is committed to IE 11 support throughout its remaining support lifespan, it would be nice to see this addressed somehow in the library.
It looks like adding the viewBox
attribute to the root SVG element would potentially fix the issue. So perhaps it could be added internally upon generation?
Document use-case against CSS
Hello! Nice repo :)
What do you think is the main use-case to prefer static images against HTML elements with CSS applied?
UTF-8 characters?
Does it supports with utf8 like japanese name or something similar?
Saving the generated image
Kudos for the hard-work. Please how can i save the image file in a folder after generation?
Thanks.
Set image height
Hi. How I can set image height on avatar generation? I need render image: 520x360
Wordpress Plugin
Hi There,
Would you be interested in turning this into a Wordpress Plugin for generating a custom default avatar for comments? I would be very keen to use something like that. The idea would be to use their gravatar
by default, but if they didn't have one, then fall back to this library to generate an image with their initials and a random color. You've done all the hard work so turning into a plugin would be pretty straightforward.
Cheers
Abe
Add PHP 5.6 support
Installation failed
Beacause
Problem 1
- Installation request for rackbeat/laravel-ui-avatars ^0.7.0 -> satisfiable by rackbeat/laravel-ui-avatars[0.7].
- Conclusion: remove lasserafn/php-initial-avatar-generator 4.0.2
- Conclusion: don't install lasserafn/php-initial-avatar-generator 4.0.2
- rackbeat/laravel-ui-avatars 0.7 requires lasserafn/php-initial-avatar-generator ^3.0 -> satisfiable by lasserafn/php-initial-avatar-generator[3.0.0, 3.0.1, 3.0.2, 3.0.3].
- Can only install one of: lasserafn/php-initial-avatar-generator[3.0.0, 4.0.2].
- Can only install one of: lasserafn/php-initial-avatar-generator[3.0.1, 4.0.2].
- Can only install one of: lasserafn/php-initial-avatar-generator[3.0.2, 4.0.2].
- Can only install one of: lasserafn/php-initial-avatar-generator[3.0.3, 4.0.2].
- Installation request for lasserafn/php-initial-avatar-generator (locked at 4.0.2) -> satisfiable by lasserafn/php-initial-avatar-generator[4.0.2].
Laravel use
Hello, can you please offer up guidance on how to use your library for laravel?
What provider to i register and what use string do i use?
Thank you very much.
Update readme with two new fonts.
Add the two missing fonts to the readme.
PHP 8 Support
main package lasserafn/php-initial-avatar-generator supports php8 as well, but
lasserafn/php-initials required 7.1+, it would be nice to support PHP 8.0 completely.
Result output
Hello,
$resim = $avatar->name('Lasse Rafn')
->length(2)
->fontSize(0.5)
->size(96)// 48 * 2
->background('#8BC34A')
->color('#fff')
->generate()
->stream('png', 100);
echo '<img src="' . $resim . '" width="48" height="48" style="border-radius: 100%" />';
Result:
<img src="�PNG � IHDR00��W�����IDATh��=��@�������� i���"�),�X������R�����"����R�2��"������D삤�s�]؏�qd�.��S��y9O ���@��H��x�!��!��!��!��!��!��!����\���A��P�������� ��y��fh�ۈD"L����K�C���p�\�,CQ��R)��i���l6��rɜOa��DD��z�����Q�Z�kOUU�L&DD���C����� ��GT�\�Wh��d2ɔ��#�������S��.�( ��<��\������8n��V��S���$IB,�C�^�t:�$I�,����9�w���n����;�z���l68�N��3�$IB.���px9��s��m""���/�}���m�|>�X,�0��������f� ��z�e�9�[��������4 �e1�p���i��x��j1Ob�.������?���.��A���b��h�Z��N��r��t-L���}���F��j4�(� (�J0���>u�����_�o�o�o�o�o�o���'#+X����{IEND�B`�"/>
What cloud be reason for this?
Thank you?
Gradient Colors
Can I create a gradient color fill?
Broken Return
return $avatar->name('Lasse Rafn')
->length(2)
->fontSize(0.5)
->size(96) // 48 * 2
->background('#8BC34A')
->color('#fff')
->cache()
->generate()
->stream('png', 100);
this is output showing up http://prntscr.com/hnahzh
Turkish Characters
Hello,
Can you provide a Turkish character?
Except for the Latin alphabet, these are the character:
"ş, ç, ğ, ü, ö, ı"
http://turkishbasics.com/resources/turkish-characters-html-codes.php
Thank you!
SVG support ?
Is it possible to add SVG support ? SVG is much better for this kind of pictures !
Compile Error: Cannot use lexical variable $font as a parameter name in InitialAvatar.php
Title: Compile Error: Cannot use lexical variable $font
as a parameter name in InitialAvatar.php
Description:
I encountered a Compile Error
in InitialAvatar.php
due to the use of $font
as a parameter name in a function. In PHP, lexical variables cannot be reused as parameter names within closures. This results in the following error:
[critical] Uncaught PHP Exception Symfony\Component\ErrorHandler\Error\FatalError: "Compile Error: Cannot use lexical variable $font as a parameter name" at InitialAvatar.php line 28
Steps to Reproduce:
- Use the
InitialAvatar
class in a Symfony project or any PHP project that utilizes dependency injection for configuration. - Attempt to generate an avatar, which causes the code at line 28 in
InitialAvatar.php
to execute.
Expected Behavior:
The avatar should be generated without triggering a compile error.
Proposed Solution:
Rename the $font
parameter within the affected function or closure to avoid conflicts with lexical scoping. This should resolve the compile error.
Environment:
- PHP Version: [8.2.9]
InitialAvatarGenerator
Version: v0.1.7
Thank you for your assistance! Please let me know if you need further details to resolve this issue.
Laravel Wrapper
FontAwesome only user icon works
Hey,
Two quick questions:
-
How do I load a custom font?
Running on Laravel here and generating them (not for users). Any hints? I've tried theresource_path()
and theasset()
without any luck. -
FontAwesome not all icons are supported, I've tried multiple but only seem to ge the user to work. In the example below this should render the question mark.
$image = $avatar->glyph('f128')
->font('/fonts/FontAwesome5Free-Regular-400.otf')
->size(500)
->rounded()
->background('#e9655b')
->color('#ffffff')
->generate();
return response($image->stream('png', 100))
->header('Content-Type','image/png')
->header('Pragma','public')
->header('Content-Disposition','inline; filename="1231231231231.png"')
->header('Cache-Control','max-age=60, must-revalidate');
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.