我正在创建一个简单的PHP精灵图像生成器,我能够计算精灵图像的可能宽度和高度,但我坚持创建透明画布并将图像放入其中。
现在假设精灵图像的宽度是200x500px(我正在创建垂直精灵)。放在精灵图像中的图像是这样的数组:
array('logo.png','delete.png','open.png');
你将如何将这些图像放入精灵中?
答案 0 :(得分:0)
$path = '/img/';
$imgs = array('logo.png','delete.png','save.png');//images needed to be put in the sprite
$canvasWidth= 0;
$canvasHeight = 0;
//calculate the posible canvas width and height
foreach($imgs as $val)
{
$info = getimagesize($path.basename($val));
$width=$info[0];
$height=$info[1];
$canvasHeight +=$height;
if($canvasWidth < $width){
$canvasWidth = $width;
}
}
// create our canvas
$img = imagecreatetruecolor($canvasWidth, $canvasHeight);
$background = imagecolorallocatealpha($img, 255, 255, 255, 127);
imagefill($img, 0, 0, $background);
imagealphablending($img, false);
imagesavealpha($img, true);
// start placing our icons from the top down.
$pos = 0;
foreach($imgs as $val){
$tmp = imagecreatefrompng($path.basename($val));
$w=imagesx($tmp);
$h=imagesy($tmp);
imagecopy($img, $tmp, 0, $pos, 0, 0, $w, $h);
$pos += $h;
imagedestroy($tmp);
}
// create our final output image.
imagepng($img, $path.'sprite.png');