Plug n play avatar, turn name, email, and any other string into beautiful avatar (or gravatar), effortless.

Overview

laravolt/avatar

SensioLabsInsight Travis Coverage Status

Preview

Display unique avatar for any user based on their (initials) name.

Preview

Preview

Installation

This package originally built for Laravel, but can also be used in any PHP project.

Read more about integration with PHP project here.

Laravel >= 5.2:

composer require laravolt/avatar

Laravel 5.1:

composer require laravolt/avatar ~0.3

Service Provider & Facade

Note: only for Laravel 5.4 and below, because since Laravel 5.5 we use package auto-discovery.

Laravolt\Avatar\ServiceProvider::class,

...

'Avatar'    => Laravolt\Avatar\Facade::class,

Publish Config (optional)

php artisan vendor:publish --provider="Laravolt\Avatar\ServiceProvider"

This will create config file located in config/laravolt/avatar.php.

Lumen Service Provider

$app->register(Laravolt\Avatar\LumenServiceProvider);

Usage

Output as base64

//this will output data-uri (base64 image data)
//something like data:image/png;base64,iVBORw0KGg....
Avatar::create('Joko Widodo')->toBase64();

//use in view
//this will display initials JW as an image
<img src="{{ Avatar::create('Joko Widodo')->toBase64() }}" />

Save as file

Avatar::create('Susilo Bambang Yudhoyono')->save('sample.png');
Avatar::create('Susilo Bambang Yudhoyono')->save('sample.jpg', 100); // quality = 100

Output as Gravatar

Avatar::create('[email protected]')->toGravatar();
// Output: http://gravatar.com/avatar/0dcae7d6d76f9a3b14588e9671c45879

Avatar::create('[email protected]')->toGravatar(['d' => 'identicon', 'r' => 'pg', 's' => 100]);
// Output: http://gravatar.com/avatar/0dcae7d6d76f9a3b14588e9671c45879?d=identicon&r=pg&s=100

Gravatar parameter reference: https://en.gravatar.com/site/implement/images/

Output as SVG

Avatar::create('Susilo Bambang Yudhoyono')->toSvg();

You may specify custom font-family for your SVG text.

<head>
    <!--Prepare custom font family, using Google Fonts-->
    <link href="https://fonts.googleapis.com/css?family=Laravolt" rel="stylesheet">

    <!--OR-->

    <!--Setup your own style-->
    <style>
    @font-face {
        font-family: Laravolt;
        src: url({{ asset('fonts/laravolt.woff')) }});
    }
    </style>
</head>
Avatar::create('Susilo Bambang Yudhoyono')->setFontFamily('Laravolt')->toSvg();

Get underlying Intervention image object

Avatar::create('Abdul Somad')->getImageObject();

The method will return an instance of Intervention image object, so you can use it for further purposes.

Non-ASCII Character

By default, this package will try to output any initials letter as it is. If the name supplied contains any non-ASCII character (e.g. ā, Ě, ǽ) then the result will depend on which font used (see config). It the font supports characters supplied, it will successfully displayed, otherwise it will not.

Alternatively, we can convert all non-ascii to their closest ASCII counterparts. If no closest coutnerparts found, those characters are removed. Thanks to Stringy for providing such useful functions. What we need is just change one line in config/avatar.php:

    'ascii'    => true,

Configuration

<?php
/*
 * Set specific configuration variables here
 */
return [

    /*
    |--------------------------------------------------------------------------
    | Image Driver
    |--------------------------------------------------------------------------
    | Avatar use Intervention Image library to process image.
    | Meanwhile, Intervention Image supports "GD Library" and "Imagick" to process images
    | internally. You may choose one of them according to your PHP
    | configuration. By default PHP's "Imagick" implementation is used.
    |
    | Supported: "gd", "imagick"
    |
    */
    'driver'    => 'gd',

    // Initial generator class
    'generator' => \Laravolt\Avatar\Generator\DefaultGenerator::class,

    // Whether all characters supplied must be replaced with their closest ASCII counterparts
    'ascii'    => false,

    // Image shape: circle or square
    'shape' => 'circle',

    // Image width, in pixel
    'width'    => 100,

    // Image height, in pixel
    'height'   => 100,

    // Number of characters used as initials. If name consists of single word, the first N character will be used
    'chars'    => 2,

    // font size
    'fontSize' => 48,

    // convert initial letter in uppercase
    'uppercase' => false,

    // Right to Left (RTL)
    'rtl' => false,

    // Fonts used to render text.
    // If contains more than one fonts, randomly selected based on name supplied
    'fonts'    => [__DIR__.'/../fonts/OpenSans-Bold.ttf', __DIR__.'/../fonts/rockwell.ttf'],

    // List of foreground colors to be used, randomly selected based on name supplied
    'foregrounds'   => [
        '#FFFFFF',
    ],

    // List of background colors to be used, randomly selected based on name supplied
    'backgrounds'   => [
        '#f44336',
        '#E91E63',
        '#9C27B0',
        '#673AB7',
        '#3F51B5',
        '#2196F3',
        '#03A9F4',
        '#00BCD4',
        '#009688',
        '#4CAF50',
        '#8BC34A',
        '#CDDC39',
        '#FFC107',
        '#FF9800',
        '#FF5722',
    ],

    'border'    => [
        'size'  => 1,

        // border color, available value are:
        // 'foreground' (same as foreground color)
        // 'background' (same as background color)
        // or any valid hex ('#aabbcc')
        'color' => 'background',

        // border radius, only works for SVG
        'radius' => 0,
    ],

    // List of theme name to be used when rendering avatar
    // Possible values are:
    // 1. Theme name as string: 'colorful'
    // 2. Or array of string name: ['grayscale-light', 'grayscale-dark']
    // 3. Or wildcard "*" to use all defined themes
    'theme' => ['*'],

    // Predefined themes
    // Available theme attributes are:
    // shape, chars, backgrounds, foregrounds, fonts, fontSize, width, height, ascii, uppercase, and border.
    'themes' => [
        'grayscale-light' => [
            'backgrounds' => ['#edf2f7', '#e2e8f0', '#cbd5e0'],
            'foregrounds' => ['#a0aec0'],
        ],
        'grayscale-dark' => [
            'backgrounds' => ['#2d3748', '#4a5568', '#718096'],
            'foregrounds' => ['#e2e8f0'],
        ],
        'colorful' => [
            'backgrounds' => [
                '#f44336',
                '#E91E63',
                '#9C27B0',
                '#673AB7',
                '#3F51B5',
                '#2196F3',
                '#03A9F4',
                '#00BCD4',
                '#009688',
                '#4CAF50',
                '#8BC34A',
                '#CDDC39',
                '#FFC107',
                '#FF9800',
                '#FF5722',
            ],
            'foregrounds' => ['#FFFFFF'],
        ],
    ]
];

Overriding config at runtime

We can overriding configuration at runtime by using following functions:

Avatar::create('Soekarno')->setDimension(100);//width = height = 100 pixel
Avatar::create('Soekarno')->setDimension(100, 200); // width = 100, height = 200
Avatar::create('Soekarno')->setBackground('#001122');
Avatar::create('Soekarno')->setForeground('#999999');
Avatar::create('Soekarno')->setFontSize(72);
Avatar::create('Soekarno')->setFont('/path/to/font.ttf');
Avatar::create('Soekarno')->setBorder(1, '#aabbcc'); // size = 1, color = #aabbcc
Avatar::create('Soekarno')->setBorder(1, '#aabbcc', 10); // size = 1, color = #aabbcc, border radius = 10 (only for SVG)
Avatar::create('Soekarno')->setShape('square');

// Available since 3.0.0
Avatar::create('Soekarno')->setTheme('colorful'); // set exact theme
Avatar::create('Soekarno')->setTheme(['grayscale-light', 'grayscale-dark']); // theme will be randomized from these two options

// chaining
Avatar::create('Habibie')->setDimension(50)->setFontSize(18)->toBase64();

Integration with other PHP project

// include composer autoload
require 'vendor/autoload.php';

// import the Avatar class
use Laravolt\Avatar\Avatar;

// create your first avatar
$avatar = new Avatar($config);
$avatar->create('John Doe')->toBase64();
$avatar->create('John Doe')->save('path/to/file.png', $quality = 90);

$config is just an ordinary array with same format as explained above (See Configuration).

Comments
  • Non-static method Laravolt\Avatar\Avatar::create() should not be called statically

    Non-static method Laravolt\Avatar\Avatar::create() should not be called statically

    Why I got this error? I follow the usage of the instruction.
    Here is my code. `public function store(RegistrationRequest $request) { //save to file $currentId = \DB::table('users')->max('id') + 1; $destinationPath = 'storage/images/users/' . $currentId . '/avatar/'; $completePath = url('/' . $destinationPath . 'default.png');

    Avatar::create(request('name'))->save($completePath);
    
    $user = User::create([
        'name'     => request('name'),
        'email'    => request('email'),
        'password' => bcrypt(request('password')),
        'avatar'   => $completePath
    ]);
    

    }`

    opened by mimimhmh 14
  • pixelperfect borders

    pixelperfect borders

    This pull request fixes borders creation. Avatar::createCircleShape and Avatar::createSquareShape adds additional transparent borders for images. For example if i make avatar 70x70px with 1px border i'll get 70x70px image, but i also get two borders: first is 1px transparent border and second my 1px border with color from config file. That happens because of improper dimensions calculations here:

    $x = $y = $this->borderSize;
    $width = $this->width - ($this->borderSize * 2);
    $height = $this->height - ($this->borderSize * 2);
    

    That make transparent border. The second border is made by intervention rectangle method.

    opened by chelout 9
  • Right to left script support

    Right to left script support

    Thanks for the great package. I know that with proper fonts, the package supports right-2-left (R2L) scripts however the direction of letters on the photo is not right. Github issue does not allow me to upload a photo but the concept is easy to imagine. Let the R2L name is wonS nhoJ (from right to left it is John snow), then the current implementation of the picture would have JS in it that is read as Snow John because of the R2L nature of the language. I can temporarily suppress the problem by allowing only one letter of the word but could be much better to support the right direction of the script.

    help wanted 
    opened by omidMolaverdi 8
  • Low contrast between background and foreground

    Low contrast between background and foreground

    In some cases, the result is a yellow avatar with white letters, which is not very easy to read. So, I would like to know, how or where I could override the getRandomForeground() to check for contrast before chossing one. Thanks!

    opened by ezeveliz 8
  • SVG output, text is not centered vertically

    SVG output, text is not centered vertically

    With SVG output, text is not centered vertically. Chrome : not well centered Edge : text is on top

    Solution : correct default value + add parameters to give an offset X, Y to the text.

    version : 2.1.0

    opened by neoteknic 8
  • setdimension() not working

    setdimension() not working

    The method setdimension() not working. The generated image always has the size 100x100

    For example:

    Avatar::create('Habibie')->setDimension(50)->setFontSize(18)->toBase64() has the size 100x100

    opened by padre 7
  • Reverse Initials

    Reverse Initials

    Thanks for the great package!

    I was wondering if you could add a config flag to reverse the initials, so for example, John Doe's avatar would be (DJ) instead of (JD).

    Thanks :)

    opened by ghost 7
  • Can't install with Laravel 5.1

    Can't install with Laravel 5.1

    I am getting an error while trying to install your Avatar package through composer:

    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Can only install one of: danielstjules/stringy[2.2.0, 1.10.0].
        - Can only install one of: danielstjules/stringy[2.2.0, 1.10.0].
        - Can only install one of: danielstjules/stringy[2.2.0, 1.10.0].
        - laravolt/avatar 1.2.0 requires danielstjules/stringy ~2.2 -> satisfiable by danielstjules/stringy[2.2.0].
        - Installation request for laravolt/avatar ^1.2 -> satisfiable by laravolt/avatar[1.2.0].
        - Installation request for danielstjules/stringy == 1.10.0.0 -> satisfiable by danielstjules/stringy[1.10.0].
    

    The required package Stringy also can't be installed on a Laravel 5.1 system. Or should I install both Stringy 1.10.0 and 2.2.0?

    opened by CptChaos 7
  • Arabic (utf8) not working

    Arabic (utf8) not working

    The package work with English only same problem #69 and #58 i try to set custom Arabic font i used setFont method and i changed path in avatar.php but it doesn't work any help pls I used the last version 4.1.4

    opened by balin09 6
  • Custom fonts not set

    Custom fonts not set

    When changing fonts in config, with command Avatar::create('NAME')->toBase64() doesn't set custom fonts, because fonts are set during __construct() function , when the $name attribute is not set. Then, when during the construct it tries to set custom fonts (with $this->getRandomFont() in applyTheme method), the getRandomElement called by getRandomFont() checks if the $name attribute is set ( if (strlen($this->name) == 0 || count($array) == 0) { ...) the attribute, during the __construct() function, is not set, because is filled only with the create function, so the custom fonts will never be set.

    opened by Release88 6
  • Changed Facade.php to Avatar.php and updated namespace to Laravolt\Av…

    Changed Facade.php to Avatar.php and updated namespace to Laravolt\Av…

    …atar\Facades to escape the Non-static method should not be called statically error when using Avatar::create, Now the Facade Alias will be Avatar => Laravolt\Avatar\Facades\Avatar::class

    opened by jayspecies 6
  • SVGs have their width and height set rendering them unresponsive

    SVGs have their width and height set rendering them unresponsive

    TL;DR: Setting the width and height constraints directly on a vector image defeats the purpose of being an svg in responsive webdesign.

    The SVGs being created have their height and width set, rendering them unable to be natively responsive in browsers. I tried setting height and width to null but to no avail. Would it be a solution to remove the width and height from the generated SVG from ->toSvg() to make them work as SVGs were intended? If constraints are needed it's never a problem to create a container for the SVG, but removing the constraints from the SVG is impossible. I'd be happy to pull request the removal of the two attributes if this is at all an interesting change.

    image
    opened by lasseeee 1
  • Using SVG with & (ampersand) breaks XML

    Using SVG with & (ampersand) breaks XML

    E.g. Romeo & Juliet

    This page contains the following errors:
    error on line 1 at column 354: xmlParseEntityRef: no name
    Below is a rendering of the page up to the first error.
    

    Is this to be expected? Should one convert to HTML-tags/remove special symbols?

    Thanks

    opened by francoism90 0
Releases(4.1.7)
Owner
Laravolt
Membuat Sistem Informasi 2 minggu jadi
Laravolt
make names from avatar name

Make Profile Image From Name Demo Of Name Like This Mana Lovez : With this package you can easily generate profile photos in different formats (for no

mohammad mohammadi 5 Nov 10, 2021
Create material deisgn avatars for users just like Google Messager. It may not be unique but looks better than Identicon or Gravatar.

Material-Design-Avatars Create material deisgn avatars for users just like Google Messager. It may not be unique but looks better than Identicon or Gr

Canbin Lin 268 Sep 14, 2022
🤹‍♀️Very simple to use Gravatar implementation for Laravel

Very simple to use Gravatar implementation for Laravel. Install, Include the Facade and then generate, simple! Installation You can install the packag

Wavey 11 May 7, 2022
Create beautiful generative background images from a string. Based on jasonlong/geo_pattern

GeoPattern This is a PHP port of jasonlong/geo_pattern. Generate beautiful tiling SVG patterns from a string. The string is converted into a SHA and a

Redeye Group 106 Aug 17, 2022
👤 Add your own default WordPress avatar.

Custom User Avatar WordPress currently only allows you to use custom avatars that are uploaded through Gravatar. Custom User Avatar enables you to use

David Artiss 13 Jan 24, 2022
The original WordPress User Avatar plugin, before it became ProfilePress

Orig User Avatar This WordPress plugin is a fork of the popular wp-user-avatar plugin, before it became ProfilePress. Compatibility with wp-user-avata

Philipp Stracker 6 Jul 17, 2021
Multiavatar is a multicultural avatar generator.

Multiavatar Multiavatar is a multicultural avatar generator. In total, it is possible to generate 12,230,590,464 cryptographically unique avatars. Ini

Multiavatar 609 Dec 29, 2022
Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.

Image Optimizer This library is handy and very easy to use optimizer for image files. It uses optipng, pngquant, jpegoptim, svgo and few more librarie

Piotr Śliwa 879 Dec 30, 2022
Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file, move it to a new directory, and returns the new source for the image.

NO LONGER MAINTAINED!!! Image Cache v. 1.0.0 Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file,

Erik Nielsen 455 Dec 30, 2022
A great looking and easy-to-use photo-management-system you can run on your server, to manage and share photos.

Lychee A great looking and easy-to-use photo-management-system. Since the 1st of April 2018 this project has moved to it's own Organisation (https://g

Tobias Reich 6.2k Dec 31, 2022
PHP Exif Library - library for reading and writing Exif headers in JPEG and TIFF files using PHP.

PEL: PHP Exif Library README file for PEL: PHP Exif Library. A library with support for reading and writing Exif headers in JPEG and TIFF images using

null 264 Dec 4, 2022
A great looking and easy-to-use photo-management-system you can run on your server, to manage and share photos.

A great looking and easy-to-use photo-management-system you can run on your server, to manage and share photos.

Lychee Organisation 2.3k Jan 1, 2023
The Tinify API allows you to compress and optimize WebP, JPEG and PNG images.

The Tinify API allows you to compress and optimize WebP, JPEG and PNG images. It is designed as a REST service. The client libraries in various languages make it very easy to interact with the Tinify API.

Devscast 10 May 13, 2022
GifFrameExtractor is a PHP class that separates all the frames (and their duration) of an animated GIF

================================ GifFrameExtractor ================================ GifFrameExtractor is a PHP class that separates all the frames (an

Clément Guillemain 173 Dec 12, 2022
Auto Image & file upload, resize and crop for Laravel eloquent model using Intervention image

Laravel ImageUp The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization. Install

QCode.in 708 Dec 22, 2022
Laragram is a simple instagram "clone" built with Laravel and Tailwind CSS

Laragram is a simple instagram "clone" built with Laravel and Tailwind CSS that gives to the users the ability to create or edit their own profiles (including profile image and description), upload images and share them among friends

null 0 Jul 24, 2021
A PHP GD + TwitterOAuth demo to dynamically generate Twitter header images and upload them via the API.

A PHP GD + TwitterOAuth demo to dynamically generate Twitter header images and upload them via the API. This enables you to build cool little tricks, like showing your latest followers or sponsors, latest content creted, a qrcode to something, a progress bar for some goal, and whathever you can think of.

Erika Heidi 172 Jan 5, 2023
⚡ Dynamically generated, customizable SVG that gives the appearance of typing and deleting text. Typing SVGs can be used as a bio on your Github profile readme or repository.

⚡ Dynamically generated, customizable SVG that gives the appearance of typing and deleting text. Typing SVGs can be used as a bio on your Github profile readme or repository.

Jonah Lawrence 2k Jan 9, 2023
A simple page view counter that store data as text and shows data as a PNG image

Image Counter A simple page view counter that store data as text and shows the counter as a PNG image.

Victor Ribeiro 10 Apr 19, 2022