Skip to content

Instantly share code, notes, and snippets.

@serhiinkh
Last active August 29, 2015 13:58
Show Gist options
  • Save serhiinkh/10412903 to your computer and use it in GitHub Desktop.
Save serhiinkh/10412903 to your computer and use it in GitHub Desktop.
<?php
error_reporting(-1);
class Avatar
{
private $path = './images/';
private $config = array(
0 => 'backgrounds',
1 => 'bodies',
2 => 'accessories',
3 => 'effects',
4 => 'faces',
5 => 'mouths',
6 => 'eyes',
7 => 'mustaches',
8 => 'hats',
9 => 'glasses',
);
public function __construct()
{
}
public static function init()
{
return new self;
}
public function run()
{
$size = isset($_GET['s']) && $_GET['s'] <= 500 ? $_GET['s'] : 200;
header('Content-Type: image/png');
if (isset($_GET['a'])) {
$options = explode('_', $_GET['a']);
if (count($options) == 10) {
$options = array_combine($this->config, array_values($options));
} else {
die('Missed some parameters');
}
$this->generateAvatar($options, $size);
} else {
$this->generateRandomAvatar($size);
}
}
public function generateAvatar($options, $size)
{
foreach($options as $folder => $filename) {
if ($folder === 'backgrounds') {
if (file_exists($this->path . $folder . '/' . $filename . '.png')) {
$background = imagecreatefrompng($this->path . $folder . '/' . $filename . '.png');
} else {
$background = imagecreatefrompng($this->path . $folder . '/0.png');
}
continue;
}
if (file_exists($this->path . $folder . '/' . $filename . '.png')) {
$layer = imagecreatefrompng($this->path . $folder . '/' . $filename . '.png');
imagecopy($background, $layer, 0, 0, 0, 0, 500, 500);
}
}
$avatar = imagecreatetruecolor($size, $size);
imagecopyresampled($avatar, $background, 0, 0, 0, 0, $size, $size, 500, 500);
$avatar = imagepng($avatar);
imagedestroy($layer);
imagedestroy($background);
return $avatar;
}
public function generateRandomAvatar($size)
{
foreach($this->config as $folder) {
if($images = glob($this->path . $folder . '/' . '*.png')) {
if ($folder === 'backgrounds') {
$background = imagecreatefrompng($images[mt_rand(0, count($images) - 1)]);
continue;
}
$layer = imagecreatefrompng($images[mt_rand(0, count($images) - 1)]);
imagecopy($background, $layer, 0, 0, 0, 0, 500, 500);
//var_dump($images[mt_rand(0, count($images) - 1)]);
}
}
$avatar = imagecreatetruecolor($size, $size);
imagecopyresized($avatar, $background, 0, 0, 0, 0, $size, $size, 500, 500);
$avatar = imagepng($avatar);
imagedestroy($layer);
imagedestroy($background);
return $avatar;
}
}
Avatar::init()->run();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment