Skip to content

Instantly share code, notes, and snippets.

@yurivictor
Last active December 17, 2015 01:29
Show Gist options
  • Save yurivictor/5528450 to your computer and use it in GitHub Desktop.
Save yurivictor/5528450 to your computer and use it in GitHub Desktop.
Better default avatars
<?php
/**
* Creates nicer default avatars
* by using first initial on flat color
*
* How to: echo create_avatar( 'yurivictor', 48 );
* Example: http://yurivictor.com/avatars
*
* @var string $user, the name of the user to create the avatar
* @var int $size, the size in px of the avatar
* @uses array_rand()
* @uses substr()
* @return html of avatar
*/
function create_avatar( $user, $size ) {
// Colors from http://flatuicolors.com/
$colors = array(
'#1abc9c',
'#2ecc71',
'#3498db',
'#9b59b6',
'#34495e',
'#16a085',
'#27ae60',
'#2980b9',
'#8e44ad',
'#2c3e50',
'#f1c40f',
'#e67e22',
'#e74c3c',
'#f39c12',
'#d35400',
'#c0392b',
);
// Get random color
$random_color = array_rand($colors, 2);
$random_color = $colors[$random_color[0]];
// Get first letter of user
$first_letter = substr( $user, 0, 1 );
// Create size CSS
$font_size = $size / 3 * 2;
$size_css = 'font-size: ' . $font_size . 'px; height: ' . $size . 'px; line-height: ' . $size . 'px; width: ' . $size . 'px;';
return '<div class="avatar" style="background-color: ' . $random_color . '; color: #fff; text-align: center; text-transform: uppercase; ' . $size_css . '">' . $first_letter . '</div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment