Php Gd精灵创作

时间:2014-04-08 02:38:19

标签: php css gd sprite

此函数的目标是在目录中创建所有.pngs的精灵。我一直在试图让它发挥作用一段时间。我已检查所有文件夹权限,并确保已启用gd库。有什么建议?

 <?php
    function spriter($dir = 'thumbs/*.png', $dest = 'thumbs/sprite.png', $spacing = 1) {

        // define icons sizes
        $icon_width = 32;
        $icon_height = 32;

        // start height of my sprite canvas
        $height = 100;

        // select all the icons and read theri height to build our canvas size.
        foreach (glob($dir) as $file) {
            list($w, $h) = getimagesize($file);
            // make sure out icon is a 32px sq icon
            if ($h == $icon_height)
                $height += ($h + $spacing);
        }

        // double our canvas height to allow for a gray-scale versions.
        $height = ($height * 2);

        // create our canvas
        $img = imagecreatetruecolor($icon_width, $height);
        $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 (glob($dir) as $file) {
            $tmp = imagecreatefrompng($file);
            if (imagesy($tmp) == $icon_height) {
                imagecopy($img, $tmp, 0, $pos, 0, 0, $icon_width, $icon_height);
                $pos += ($icon_height + $spacing);
            }
            imagedestroy($tmp);
        }

        // place all of our icons on again, but this time convert them to gray-scale
        foreach (glob($dir) as $file) {
            $tmp = imagecreatefrompng($file);
            if (imagesy($tmp) == $icon_height) {
                imagefilter($tmp, IMG_FILTER_GRAYSCALE);
                imagecopy($img, $tmp, 0, $pos, 0, 0, $icon_width, $icon_height);
                $pos +=  ($icon_height + $spacing);
            }
            imagedestroy($tmp);
        }

        // create our final output image.
        imagepng($img, $dest);
    }

&GT;

1 个答案:

答案 0 :(得分:0)

试试这个:http://github.com/namics/php-spriter

您可以根据需要进行配置: - 视网膜的多个精灵图像 - 可编辑的CSS / Less / Sass模板 - 自动变化检测 - 麻省理工学院许可