Script to dynamically generate themeroller icons

Script to dynamically generate themeroller icons


I've written a PHP script to generate ThemeRoller icons for the
specified colour, maintaining transparency where applicable.
The posted script is slightly inefficient -- to improve it, 1)
download the mask image to a local path, 2) cache the resultant
output. Also, this script likely allocates the same colour over and
over, you could track the allocated colours so they're only allocated
once.
You can pass URL parameters r, g and b in the range 0..255 to specify
the colour.
One other note: The mask doesn't appear to have any alpha info (at
least not when reading it in with the GD extension) - to account for
this the script determines the alpha based on the gray value. This
seems to work fine. If it turns out I'm wrong and the alpha value is
present (Rather than a grey value), the algorithm needs slight
tweaking.
<?php
$r = max(0, min(255, $_GET['r']));
$g = max(0, min(255, $_GET['g']));
$b = max(0, min(255, $_GET['b']));
// Fix 1: cache all of the following based on the rgb values
// Fix 2: download this file to a local path
$mask = ImageCreateFromPng('http://jqueryui.com/themeroller/images/
icons/icons.png');
$w = imageSx($mask);
$h = imageSy($mask);
$im = ImageCreateTrueColor($w, $h);
imagealphablending($im, true);
imagesavealpha($im, true);
if ($r == 255){
$trans = imageColorAllocateAlpha($im, 0, 255, 255, 127);
}
else {
$trans = imageColorAllocateAlpha($im, 255, 255, 255, 127);
}
imageFill($im, 0, 0, $trans);
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$index = imageColorAt($mask, $x, $y);
$maskRgba = imageColorsForIndex($mask, $index);
if ($maskRgba['red'] == $r && $maskRgba['green'] == $g &&
$maskRgba['blue'] == $b) {
continue;
}
$alpha = 127 - ($maskRgba['red'] / 2);
// Fix 3: Keep track of allocated colours for slight
improvement
$color = imageColorAllocateAlpha($im, $r, $g, $b, $alpha);
imageSetPixel($im, $x, $y, $color);
}
}
// end caching (Fix 1)
// change this to send the cached version
header('content-type: image/png');
imagePng($im);
?>