Giter Site home page Giter Site logo

laravolt / avatar Goto Github PK

View Code? Open in Web Editor NEW
1.9K 34.0 172.0 471 KB

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

License: MIT License

PHP 100.00%
avatar php laravel-package php-library gravatar

avatar's Introduction

laravolt/avatar

Total Downloads Monthly Downloads Run Tests Coverage Status

Preview

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

Preview

Preview

🎞️ Video Tutorial

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).

Support Us

Buy Me A Coffee

"Buy Me A Coffee"

Donate Via PayPal

paypal

Traktir Saya

Trakteer Saya

avatar's People

Contributors

ahinkle avatar chris-mackie avatar darthf1 avatar hailwood avatar intrepidws avatar kristopherchun avatar laravel-shift avatar leisurelarry avatar lipskis avatar neoteknic avatar shailesh-ladumor avatar simonschaufi avatar stylecibot avatar thijsvdanker avatar timostahl avatar tobz-nz avatar uyab avatar valenokpc avatar zahirkelloud avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

avatar's Issues

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 :)

The create() Non-static method

Laravel 5.2.

error message:

Non-static method Laravolt\Avatar\Avatar::create() should not be called statically, assuming $this from incompatible context

[Feature] Allow direct access to Image object

I recently stumbled upon your package and finally was able to try it out. As we're using VueJS for our backend and user lists we cannot use the inline base64 or to PNG file feature.

Looking at the documentation for the Image library you're using I would have to use its response('png') call to properly use it in our case (custom route taking the desired user ID). As you locked all the methods and properties I had to use reflection for the time being:

public function avatar($userId) {
    $avatar = \Avatar::create(User::findOrFail($userId)->present()->name)
        ->setFontSize(32)
        ->setShape('square')
        ->setBorder(0, 'transparent')
        ->setDimension(75, 75);

    // Due to limitations of the package we need to build the image manually here
    $reflector = new \ReflectionObject($avatar);

    $method = $reflector->getMethod('buildAvatar');
    $method->setAccessible(true);
    $method->invoke($avatar);

    $imageField = $reflector->getProperty('image');
    $imageField->setAccessible(true);
    return $imageField->getValue($avatar)->response('png');
}

This package meets our expectations perfectly, but sadly does not offer this one feature. It would be nice to have a direct "buildImage" call to get the image object itself to further return it as a response. Hope the code above helps.

Cheers and keep it up!

[3.0.0] Defaults to imagick

I was upgrading my Laravel project and got the error:

ImageMagick module not available with this PHP installation.

According to the README, the package is supposed to use gd by default. (gd was previously used in my case) The configuration in my project was not published and the default was changed somewhere between updates from gd to imagick reaching the error seen above.

I published the config and it still showed imagick as the default driver. Once I switched to gd the issue was resolved. I think the README should be updated to reflect the default is actually imagick:

By default PHP's "GD Library" implementation is used.

I didn't know if this was done on purpose or a possible mistake.

Thanks for this awesome package!

How to set padding on icon

Hi,

I just want to know if there is any possibility to set padding-left attribute on the icon? In my case the text is not centered properly.

Commendation

Wow this library is really wonder. Thumbs up to @uyab ; more grease to your elbow.

Please can you kindly work on the image quality too. This is a 70x70 image with fontsize 25px Using toBase64(). The quality is poor.
opera snapshot_2018-05-29_174539

Once again you've really done a nice job

THANK YOU

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

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

Composer require fails installation

> @php artisan package:discover


  [Symfony\Component\Debug\Exception\FatalErrorException]
  Illuminate\Support\ServiceProvider::mergeConfigFrom(): Failed opening required 'C:\Github\project\vendor\laravolt\avatar\src/../config/config.php' (include_path='.;C:\php\pear')


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255

Installation failed, reverting ./composer.json to its original content.

I have no idea why this is happening

How to set font?

Hi.
My website is using Simplified Chinese, so many users will use Chinese username, I need to determine the first character of username is Chinese, English(letters) or integer, and then decide which font to use, but your setFont() function don't have any parameters, What should I do?

Uppercase doesn't work...

When I first generate app.php, it came without

'uppercase' => true,

I checked it in the github doc, and added it, but it is not working, still get it in lowercase.

Here is how I use it in my view:

<img src="{!! Auth::getUser()->avatar ?? Avatar::create(Auth::getUser()->email)->toBase64() !!}">

Help :)

I am new to all-things Composer and I am having a hard time making this work.

After installing by going composer require laravolt/avatar then I have this.

require '../../php/vendor/autoload.php';
echo Avatar::create('test')→toBase64();

I am getting all sorts of errors and for the life of me I can’t make it work, no matter what I tried.

Some help for the newbie?:)

Update:

I kind of figured it out, but here's where I am at now:

Fatal error: Uncaught RuntimeException: A facade root has not been set. in vendor/illuminate/support/Facades/Facade.php

Uppercase all letters support

Like my name is Joey, Now I will get Jo but I want to get JO. How about add a uppercase config so people can choose whether upcase all the letters.

5.1 "Your requirements could not be resolved to an installable set of packages"

Did $ composer require laravolt/avatar ~0.3

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravolt/avatar 0.3.0 requires intervention/image 2.3.2 -> satisfiable by intervention/image[2.3.2].
    - laravolt/avatar 0.3.1 requires intervention/image 2.3.2 -> satisfiable by intervention/image[2.3.2].
    - laravolt/avatar 0.3.2 requires intervention/image 2.3.2 -> satisfiable by intervention/image[2.3.2].
    - Conclusion: don't install intervention/image 2.3.2
    - Installation request for laravolt/avatar ~0.3 -> satisfiable by laravolt/avatar[0.3.0, 0.3.1, 0.3.2].

Initial from email

Input
"[email protected]"

Current Output
UY

Expected Output
UE

Avatar should detect separator other than space. Maybe via config file.

...
'delimiter' => [' ', '.', '_'],
...

Add LICENSE.md

The MIT license is already chosen in composer.json, but for many potential users of this package it would be handy to have a easily visible LICENSE.md.

utf8 support

this package doesn't support utf8 characters? it cant generate avatar using Arabic characters.

To save base:64 in database, you must cast to string.

To save the base:64 format in a database, you must cast to string.

$user->avatar_picture = (string) Avatar::create($this->name)->toBase64();
$user->avatar_picture->save();

It would be nice to add this in the documentation!

Update dependencies

On the latest update I got the following error:

*******************************************
 /!\ Warning, you're using a deprecated
 ¨¨¨ version of Carbon, we will soon stop
     providing support and update for 1.x
     versions, please upgrade to Carbon 2.
*******************************************

Most features of Carbon 1 are still available in Carbon 2.
See how to migrate: https://carbon.nesbot.com/docs/#api-carbon-2

You can run './vendor/bin/upgrade-carbon' to get help in updating carbon and other frameworks and libraries that depend on it.

This error is because an old version of illuminate/support is used. A fix by the author of the package was already provided.
Would be awesome, if we can update the dependencies.

Since I can´t test it at the moment, I can´t open a pull request for now.

defaultFont is always applied

$this->font = $this->defaultFont; in function setRandomFont always get called. Seems like break must be changed to return;

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
]);

}`

class Image not found

as this package is using intervention , so unless i add the provider and the facade for intervention to the app/config aswell , the class not found error keeps popping up every now and then 😢

Does this work with ImageMagick?

I get an error trying to use Avatar::create($user->name)->toBase64() I get presented with the following error message:

FatalErrorException in Font.php line 85:
Call to undefined function Intervention\Image\Gd\imagettfbbox()

Is it possible to use with ImageMagick?

Can't composer install...

From bash..

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Can only install one of: intervention/image[2.3.2, 2.3.5].
- Can only install one of: intervention/image[2.3.5, 2.3.2].
- Can only install one of: intervention/image[2.3.2, 2.3.5].
- laravolt/avatar 1.2.0 requires intervention/image 2.3.2 -> satisfiable by intervention/image[2.3.2].
- Installation request for laravolt/avatar ^1.2 -> satisfiable by laravolt/avatar[1.2.0].
- Installation request for intervention/image == 2.3.5.0 -> satisfiable by intervention/image[2.3.5].

Config file inside a folder?

Is there a specific reason why the config file is being published inside the config/laravolt folder? It does not seem necessary to be honest and makes the structure look ugly.

I would rather have all my config files displayed at once, once I open up the config folder tree.

Text vertical alignment issue with imagick and toBase64

Had to switch to imagick for better image quality but now text is not aligned properly inside the icon with toBase64, text was aligned correctly with GD Library without any issues. I am using an Arabic font.

Image of Avatar

Thanks :)

Class 'Avatar' not found

Hey there!
i've a problem with this 'Avatar'
My version of laravel is 5.3, I do not know if there is a bug for this.

BUG
Captura de pantalla de 2019-03-15 15-19-01

My controller part 1
Captura de pantalla de 2019-03-15 15-23-09

My controller part 2
Captura de pantalla de 2019-03-15 15-37-07

Provider and aliase
Captura de pantalla de 2019-03-15 15-54-23
Captura de pantalla de 2019-03-15 15-54-27

Composer.json
Captura de pantalla de 2019-03-15 15-58-50

Any suggestions? thanks!

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!

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?

SVG generation looks off in firefox

image

This was a file saved with the ->toSvg() method with default settings. The avatar looks fine in all other browsers I have tried (Chrome & Safari)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.