此函数将根据文件类型和尺寸从目录中的所有图像创建一个精灵。我在脚本中面临的唯一问题是我需要精灵是水平的,而这个函数只输出一个垂直的图像。有关进行所需更改的任何建议?任何帮助,将不胜感激。
<?php
class images_to_sprite{
function images_to_sprite($folder,$output,$x,$y){
$this->folder = ($folder = 'myfolder'); // Folder name to get images from, i.e.
$this->filetypes = array('jpg'=>true,'png'=>true,'jpeg'=>true,'gif'=>true); // Acceptable file extensions
$this->output = ($output ? $output : 'mysprite'); // Output filenames, mysprite.png and mysprite.css
$this->x = '100'; // Width of images to consider
$this->y = '100'; // Heigh of images to consider
$this->files = array();
}
function create_sprite(){
$basedir = $this->folder;
$files = array();
// Read through the directory for suitable images
if($handle = opendir($this->folder))
{
while (false !== ($file = readdir($handle)))
{
$split = explode('.',$file);
// Ignore non-matching file extensions
if($file[0] == '.' || !isset($this->filetypes[$split[count($split)-1]]))
continue;
// Get image size and ascertain it has the correct dimensions
$output = getimagesize($this->folder.'/'.$file);
if($output[0] != $this->x && $output[1] != $this->y)
continue;
// Image will be added to sprite, add to array
$this->files[$file] = $file;
}
closedir($handle);
}
// yy is the height of the sprite to be created, basically X * number of images
$this->yy = $this->y * count($this->files);
$im = imagecreatetruecolor($this->x,$this->yy);
// Add alpha channel to image (transparency)
imagesavealpha($im, true);
$alpha = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im,0,0,$alpha);
// Append images to sprite and generate CSS lines
$i = $ii = 0;
$fp = fopen($this->output.'.css','w');
fwrite($fp,'.'.$this->output.' { width: '.$this->x.'px; height: '.$this->y.'px; background-image: url('.$this- >output.'.png); text-align:center; }'."\n");
foreach($this->files as $key => $file)
{
fwrite($fp,'.'.$this->output.(++$ii).' { background-position: -0px -'.($this->y*$i).'px; }'."\n");
$im2 = imagecreatefrompng($this->folder.'/'.$file);
imagecopy($im,$im2,0,($this->y*$i),0,0,$this->x,$this->y);
$i++;
}
fclose($fp);
imagepng($im,$this->output.'.png'); // Save image to file
imagedestroy($im);
}}
$class = new images_to_sprite('imagefolder','sprite',63,63);
$class->create_sprite();?>