Exiba um avatar exclusivo para qualquer usuário com base em seu nome (iniciais).
Este pacote foi originalmente construído para Laravel, mas também pode ser usado em qualquer projeto PHP.
Leia mais sobre integração com projeto PHP aqui.
composer require laravolt/avatar
composer require laravolt/avatar ~ 0.3
Nota: apenas para Laravel 5.4 e anteriores, pois desde o Laravel 5.5 usamos a descoberta automática de pacotes.
Laravolt Avatar ServiceProvider::class,
...
' Avatar ' => Laravolt Avatar Facade::class,
php artisan vendor:publish -- provider ="Laravolt Avatar ServiceProvider "
Isso criará um arquivo de configuração localizado em config/laravolt/avatar.php
.
$ app -> register ( Laravolt Avatar LumenServiceProvider);
//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() }}" />
Avatar:: create ( ' Susilo Bambang Yudhoyono ' )-> save ( ' sample.png ' );
Avatar:: create ( ' Susilo Bambang Yudhoyono ' )-> save ( ' sample.jpg ' , 100 ); // quality = 100
Avatar:: create ( ' [email protected] ' )-> toGravatar ();
// Output: http://gravatar.com/avatar/0c5cbf5a8762d91d930795a6107b2ce5814a6ab26e60c7ec6b75bc81c7dfe3ee
Avatar:: create ( ' [email protected] ' )-> toGravatar ([ ' d ' => ' identicon ' , ' r ' => ' pg ' , ' s ' => 100 ]);
// Output: http://gravatar.com/avatar/0c5cbf5a8762d91d930795a6107b2ce5814a6ab26e60c7ec6b75bc81c7dfe3ee?d=identicon&r=pg&s=100
Referência do parâmetro Gravatar: https://docs.gravatar.com/api/avatars/images/
Avatar:: create ( ' Susilo Bambang Yudhoyono ' )-> toSvg ();
Você pode especificar uma família de fontes personalizada para seu texto SVG.
< 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 ();
Avatar:: create ( ' Abdul Somad ' )-> getImageObject ();
O método retornará uma instância do objeto de imagem de intervenção, para que você possa usá-lo para outros fins.
Por padrão, este pacote tentará exibir qualquer letra inicial como está. Se o nome fornecido contiver qualquer caractere não-ASCII (por exemplo, ā, Ě, ǽ), então o resultado dependerá da fonte usada (veja configuração). Se a fonte suportar caracteres fornecidos, ela será exibida com êxito, caso contrário, não.
Alternativamente, podemos converter todos os não-ascii em seus equivalentes ASCII mais próximos. Se nenhuma contraparte mais próxima for encontrada, esses caracteres serão removidos. Obrigado ao Stringy por fornecer funções tão úteis. O que precisamos é apenas alterar uma linha em config/avatar.php
:
' ascii ' => true,
<?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 ' ],
],
]
];
Podemos substituir a configuração em tempo de execução usando as seguintes funções:
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 ();
// 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
é apenas um array comum com o mesmo formato explicado acima (veja Configuração).