Skip to content

Instantly share code, notes, and snippets.

@vemacs
Forked from tonybruess/Skin.php
Last active August 29, 2015 13:58
Show Gist options
  • Save vemacs/10012894 to your computer and use it in GitHub Desktop.
Save vemacs/10012894 to your computer and use it in GitHub Desktop.
<?php
include 'WideImage/WideImage.php';
include 'Skin.php';
# setup uri
$uri = str_replace(".png", "", explode('/', trim($_GET['q'], '/')));
# is retina?
$retina = strpos($uri[count($uri) - 1], "@2x");
$uri = str_replace("@2x", "", $uri);
# setup variables
$username = $uri[0] == null ? 'char' : $uri[0];
$size = $uri[1] == null ? '32' : $uri[1];
if($size > 1024) {
$url = '//' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
$url = str_replace($size, "1024", $url);
die(header('Location: ' . $url));
}
if($retina) $size = $size * 2;
# get skin
$result = Skin::get($username);
$img = $result[0];
$mime = $result[1];
# has helmet?
$bg = $img->getColorAt(0,0);
$hasHelmet = hasHelmet($img, $mime);
function hasHelmet($img, $mime) {
if($mime != "image/png") return false;
for($i = 0; $i < 8; $i++) {
for($j = 0; $j < 8; $j++) {
$color = $img->getRGBAt(40 + $i, 8 + $j);
if($color['red'] == 255 && $color['green'] == 255 && $color['blue'] == 255 && $color['alpha'] == 0) continue;
if($color['alpha'] < 127) return true;
}
}
return false;
}
# setup helm if has helmet
if($hasHelmet) {
$helm = $img->crop(40, 8, 8, 8);
}
# crop image to just head
$head = $img->crop(8, 8, 8, 8);
# merge head and helm if has helm
if ($hasHelmet) {
$head = $head->merge($helm);
}
# resize and show the result
$final = $head->resize($size);
$final->output(".png");
?>
<?php
class Skin {
public static function get($username) {
$steve = in_array(strtolower($username), array("steve", "player", "default"));
if(!$steve) $contents = self::fetch('http://skins.minecraft.net/MinecraftSkins/' . $username . '.png');
$defaultImage = WideImage::load("char.png");
$defaultType = "image/png";
if ($steve || $contents === false) {
$img = $defaultImage;
$type = $defaultType;
} else {
try {
$img = WideImage::load($contents);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type = $finfo->buffer($contents);
} catch (Exception $e) {
$img = $defaultImage;
$type = $defaultType;
}
}
return array($img, $type);
}
private static function fetch($url) {
$handle = curl_init($url);
if (false === $handle) {
return false;
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15")); // request as if Firefox
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_TIMEOUT_MS, 1000);
$contents = curl_exec($handle);
curl_close($handle);
return $contents;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment