sparkline.php
<?
// //////////////////////////////////////////////////////////
// sparkline.php
// sparkline.php?123456789159843695782554
//
// process parameters
$query = $_SERVER["QUERY_STRING"];
if (empty($query))
die;
// only numbers
$numValues = strlen($query);
for ($i = 0; $i < $numValues; $i++)
$hours[$i] = intval($query[$i]);
// upper limit
$maxValue = max($hours);
if ($maxValue == 0)
$maxValue = 1;
// bars' configuration
$barWidth = 3;
$barHeight = 10;
$padding = 1;
$minGray = 0.3;
$maxGray = 1.0;
$width = $numValues * ($barWidth+$padding) - 1;
$height = $barHeight;
// add borders
$width += 2;
$height += 2;
// create new image, full color range
$img = imagecreatetruecolor($width, $height);
imageantialias ($img, true);
imagealphablending($img, false);
imagesavealpha ($img, true);
// transparent background
$background = imagecolorallocatealpha($img, 0,0,0, 127);
imagefilledrectangle ($img, 1,1, $width-2,$height-2, $background);
imagecolortransparent($img, $background);
// black border
$black = imagecolorallocatealpha($img, 0,0,0, 0);
imagerectangle($img, 0,0, $width-1,$height-1, $black);
// sparklines
$x = 1;
foreach ($hours as $hour)
{
$intensity = $hour/$maxValue;
// scale to prevent too bright/dark colors
if ($intensity > 0)
$intensity = $minGray + ($maxGray-$minGray)*$intensity;
// the higher the number, the darker (not brighter)
$intensity = 1 - $intensity;
// convert to grayscale (red == green == blue)
$gray = imagecolorallocatealpha($img, 0xFF*$intensity, // red
0xFF*$intensity, // green
0xFF*$intensity, // blue
0x7F*$intensity); // alpha
// draw single bar
imagefilledrectangle($img, $x,1, $x+$barWidth-1,$barHeight, $gray);
// next one
$x += $barWidth + $padding;
}
// send to client, use some caching
$secondsCache = 3600*24*7+1;
header("Content-type: image/png");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", time())." GMT");
header("Cache-Control: max-age=$secondsCache");
header("Expires: ".gmdate("D, d M Y H:i:s", time()+$secondsCache)." GMT");
imagepng($img);
?>