#!/usr/bin/env php
<?php
/* Tiny PHP sprites generator
 * Written by Georgi Chorbadzhiyski (georgi@unixsol.org)
 * Released into PUBLIC DOMAIN
 * Do whatever you like with this code
 */
    
error_reporting(E_ALL);

    
$output_img "sprites.png";
    
$output_css "sprites.css";
    
$output_html "sprites.html";

    
$files = array();
    
$max_width 0;
    
$total_height 0;

    
// Read file info
    
foreach(glob("*.png") as $file) {
        if (
$file == $output_img)
            continue;
        
$img getimagesize($file);
        
$files[$file]["width"] = $img[0];
        
$files[$file]["height"] = $img[1];
        
$files[$file]["size"] = filesize($file);
        
$max_width max($max_width$img[0]);
        
$total_height += $img[1];
    }
    if (!
max_width || !$total_height) {
        print 
"Hmm...something is wrong with the input files.\n";
        exit;
    }

    
$imgpad 6/* Must be even */
    
$img imagecreatetruecolor($max_width$total_height + (count($files)*$imgpad));
    
imagealphablending($imgfalse);
    
imagesavealpha($imgtrue);
    
$color imagecolorallocatealpha($img0x000x000x00127);
    
imagecolortransparent($img$color);
    
imagefill($img00$color);

    
// Build image, css and html
    
$y $imgpad 2;
    
$html $css "";
    foreach (
$files as $file => $data) {
        
$srcimg imagecreatefrompng($file);
        
imagealphablending($srcimgfalse);
        
imagesavealpha($srcimgtrue);
        
imagecopy($img$srcimg0$y00$data["width"], $data["height"]);
        
imagedestroy($srcimg);

        
$class sprintf("img_%s"preg_replace("/[^A-Za-z0-9_]/","",preg_replace("/\.png/","",$file)));
        
$css .= sprintf(".%s { display:block; width:%dpx; height:%dpx; background:transparent url(%s) 0px %dpx no-repeat; }\n",
            
$class,
            
$data["width"], $data["height"],
            
$output_img,
            -
$y);
        
$html .= "<span class=\"$class\"></span>\n";

        
$y += $data["height"] + $imgpad;
    }

    
// Save image
    
imagepng($img$output_img9);
    
imagedestroy($img);

    
// Save css
    
file_put_contents($output_css$css);

    
// Save demo html
    
file_put_contents($output_html,
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">
<html>
<head>
    <link href=\"
{$output_css}\" rel=\"stylesheet\" type=\"text/css\">
    <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">
    <style type=\"text/css\">
body { background:silver; color:black; }
span { float:left; }
span:hover { background-color:#444; }
    </style>
</head>
<body>
<p><a href=\"http://georgi.unixsol.org/programs/css_sprites/\">Tiny public domain PHP sprites generator</a>
(<a href=\"http://georgi.unixsol.org/programs/css_sprites/sprites_source.php\">source</a>)</p>
<p>The image<br /><img src=\"
{$output_img}\" alt=\"img\"></p>
<p>Individual sprites:</p>
<p>
{$html}</p>
</body>
</html>"
);

    print 
"Done, open {$output_html} to see the end result.\n";
?>