You are on page 1of 21

Generated Documentation

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Contents
Package SpriteGenerator Procedural Elements 2
SpriteGenerator.php 2
Package SpriteGenerator Classes 4
Class SpriteGenerator 4
Var $defaultOutput 5
Var $_pairs 5
Constructor SpriteGenerator 5
Method batchSprites 5
Method generateSprite 5
Method setDirectory 6
Method setPairs 6
Method _createImageFromFile 6
Method _parseDirectory 6
Method _writeSprite 7
Appendices 8
Appendix A - Class Trees 9
SpriteGenerator 9
Appendix B - README/CHANGELOG/INSTALL 10
README 11
Appendix C - Source Code 13
Package SpriteGenerator 14
source code: SpriteGenerator.php 15

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu
Page 1 of 18
Package SpriteGenerator Procedural
Elements

SpriteGenerator.php
Copyright (c) 2008, Chris Morrell All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice,


this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice,


this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

Neither the name of Chris Morrell nor the names of its


contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Package SpriteGenerator

Author Chris Morrell / cmorrell.com

Author Saul Rosenbaum / visualchutzpah.com

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 2 of 18
Copyright Copyright (c) 2008 Chris Morrell

Filesource Source Code for this file

License New

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 3 of 18
Package SpriteGenerator Classes

Class SpriteGenerator
[line 84]
CSS Sprite Generator Class
Generates CSS sprite pairs either based on an array of pairs or from a directory based
on filename rules. Two examples:

1 <?php
2 require 'SpriteGenerator.php';
3 $sg = new SpriteGenerator(array(array('file1.gif'), array('file1b.gif'));
4 $sg-> batchSprites();
5 ?>

The above code will overwrite file1.gif with a image containing file1.gif and file1b.gif vertically stacked.

1 <?php
2 require 'SpriteGenerator.php';
3 $sg = new SpriteGenerator('./images/');
4 $sg-> batchSprites();
5 ?>

The above code will parse ./images/ and create sprites on using file.ext and file_over.ext (for example file1.gif and
file1_over.gif will be converted to file1.gif).

If you would like to use a different matching method, pass a regular expression as the $match1 and $match2
variables. The first substring match is the filename base (in the above example "file1") and the second
substring match is the extension (in the above example "gif"). If you'd rather use something like
"myfile-a.gif" and "myfile-b.gif" you could use the following two regular expressions:

Match 1: /^([a-z0-9]+)-a\.(jpg|jpeg|jpe|png|gif)$/i Match 2: /^([a-z0-9]+)-b\.(jpg|jpeg|jpe|png|gif)$/i

Package SpriteGenerator

Author Saul Rosenbaum / visualchutzpah.com

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 4 of 18
Author Chris Morrell / cmorrell.com

Copyright Copyright (c) 2008 Chris Morrell

License New

SpriteGenerator::$defaultOutput

string = 'png' [line 99]

Set this to the format you would like to output (gif, png, jpeg)

SpriteGenerator::$_pairs

array = array() [line 92]

Internal variable to hold each pair of images to be turned into a sprite

Constructor SpriteGenerator function SpriteGenerator::SpriteGenerator([$input = null], [$match1 = '/^([a-z0-


9]+)\.(jpg|jpeg|jpe|png|gif)$/i'], [$match2 = '/^([a-z0-9]+)_over\.(jpg|jpeg|jpe|png|gif)$/i']) [line 111]
Function Parameters:

array|string $input

$match1

$match2

Contructor
Pass the constructor an array and it'll use that array as its pair images. Pass it a
directory and it'll parse that directory and create pairs based on the images found there.

void function SpriteGenerator::batchSprites() [line 174]


Batch creates sprites for all image pairs

resource function SpriteGenerator::generateSprite($file1, $file2) [line 191]


Function Parameters:

string $file1

string $file2

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 5 of 18
Generates a sprite image based on two files

boolean function SpriteGenerator::setDirectory($directory, [$match1 = '/^([a-z0-9]+)\.(jpg|jpeg|jpe|png|gif)$/i'],


[$match2 = '/^([a-z0-9]+)_over\.(jpg|jpeg|jpe|png|gif)$/i']) [line 141]
Function Parameters:

string $directory

$match1

$match2

Sets the directory to generate pairs from

boolean function SpriteGenerator::setPairs([$pairs = array()]) [line 127]


Function Parameters:

array $pairs

Setter function for _pairs

resource function SpriteGenerator::_createImageFromFile($filename) [line 222]


Function Parameters:

string $filename

Internal method that creates an image resource from a file name (choosing the correct
GD function based on file extension)

void function SpriteGenerator::_parseDirectory($directory, $match1, $match2) [line 152]


Function Parameters:

string $directory

$match1

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 6 of 18
$match2

Parses a passed directory

void function SpriteGenerator::_writeSprite($image, $filename) [line 254]


Function Parameters:

resource $image

string $filename

Internal method for writing a sprite to disk

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 7 of 18
Appendices

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 8 of 18
Appendix A - Class Trees
Package SpriteGenerator

SpriteGenerator
SpriteGenerator

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 9 of 18
Appendix B -
README/CHANGELOG/INSTALL

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 10 of 18
README

Sprite Generator v01


Quick Notes:

Authors:

Saul Rosenbaum / visualchutzpah.com


Chris Morrell / cmorrell.com

This is a quick little utility to take some of the pain out of


stitching together graphics for use as css-sprites it was conceived
to fit a specific workflow. The class is nicely commented,
read on for a quick overview.

To utilize it follow the simple steps below:

1. As you normally would create a folder of individual


graphics that represent the states of your graphics.

2. Designate your over-state with '_over' so if your neutral state was 'home.gif'
it's corresponding over state would be 'home_over.gif' [likewise if
you want to change this default behavior you can pass your own
pattern to the SpriteGenerator constructor - see line 37 of the
class for the expected arguments]

Example:
working_directory
spriteGen.php
images
a00.png
a00_over.png
a01.png
a01_over.png

3. MAKE A COPY YOUR GRAPHICS - this class consumes the individual graphics,
We fully reccomend you work on copies of your images

4. Pass the directory path containing your individual graphics to the class [line 190]
$sg = new SpriteGenerator("./images/");
If all has gone as expected you should now have:

Results:
working_directory
spriteGen.php
images
a00.png
a01.png

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 11 of 18
Where a00.png is a combined image of a00.png and a00_over.png stitched together vertically.

Notes on Color Space:


The class can deal with any 'web-friendly' format of graphic - in regards to stitching gifs -
if both states don't share the same color palette you may get some artifacts where the palette
of the overstate gets remapped to the palette of the neutral state, I'm sure it's addressable
programatically but working with pngs and outputting as gifs is a simple enough solution.

Possible Enhancements:
- The most obvious one is support for a variable number of states.
- The addition of a vertical offset variable - we didn't need it but adding it
to the generateSprite method would be simple.
- I suppose there are situations when you want to work horizontally rather than vertically -
but I can't imagine what they may be.
- Some type of GUI front-end to make this process drag and drop from the desktop
(perhaps via PHP-GTK).

Additional Info:
- info on css-sprites can be found here: http://www.alistapart.com/articles/sprites
- info on the benefits of reducing http requests canbe found here:
http://yuiblog.com/blog/2006/11/28/performance-research-part-1/

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 12 of 18
Appendix C - Source Code

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 13 of 18
Package SpriteGenerator

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 14 of 18
File Source for SpriteGenerator.php
Documentation for this file is available at SpriteGenerator.php

1 <?php
2 /**
3 * Copyright (c) 2008, Chris Morrell
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without modification,
7 * are permitted provided that the following conditions are met:
8 *
9 * - Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * - Redistributions in binary form must reproduce the above copyright notice,
13 * this list of conditions and the following disclaimer in the documentation
14 * and/or other materials provided with the distribution.
15 *
16 * - Neither the name of Chris Morrell nor the names of its
17 * contributors may be used to endorse or promote products derived from this
18 * software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
24 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
27 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 * @category Utilities
32 * @package SpriteGenerator
33 * @copyright Copyright (c) 2008 Chris Morrell
34 * @author Saul Rosenbaum / visualchutzpah.com
35 * @author Chris Morrell / cmorrell.com
36 * @license New BSD (see above)
37 */
38
39 /**
40 * CSS Sprite Generator Class
41 *
42 * Generates CSS sprite pairs either based on an array of pairs or from a
43 * directory based on filename rules. Two examples:
44 *
45 * <code>
46 * <?php
47 * require 'SpriteGenerator.php';
48 * $sg = new SpriteGenerator(array(array('file1.gif'), array('file1b.gif'));
49 * $sg->batchSprites();
50 * ?>
51 * </code>
52 *
53 * The above code will overwrite file1.gif with a image containing file1.gif
54 * and file1b.gif vertically stacked.
55 *
56 * <code>
57 * <?php
58 * require 'SpriteGenerator.php';
59 * $sg = new SpriteGenerator('./images/');
60 * $sg->batchSprites();
61 * ?>
62 * </code>
63 *
64 * The above code will parse ./images/ and create sprites on using file.ext and
65 * file_over.ext (for example file1.gif and file1_over.gif will be converted to
66 * file1.gif).
67 *

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 15 of 18
68 * If you would like to use a different matching method, pass a regular expression
69 * as the $match1 and $match2 variables. The first substring match is the filename
70 * base (in the above example "file1") and the second substring match is the extension
71 * (in the above example "gif"). If you'd rather use something like "myfile-
a.gif" and
72 * "myfile-b.gif" you could use the following two regular expressions:
73 *
74 * Match 1: /^([a-z0-9]+)-a\.(jpg|jpeg|jpe|png|gif)$/i
75 * Match 2: /^([a-z0-9]+)-b\.(jpg|jpeg|jpe|png|gif)$/i
76 *
77 * @category Utilities
78 * @package SpriteGenerator
79 * @copyright Copyright (c) 2008 Chris Morrell
80 * @author Saul Rosenbaum / visualchutzpah.com
81 * @author Chris Morrell / cmorrell.com
82 * @license New BSD (see above)
83 */
84 class SpriteGenerator
85 {
86 /**
87 * Internal variable to hold each pair of images to be
88 * turned into a sprite
89 *
90 * @var array
91 */
92 var $_pairs = array();
93
94 /**
95 * Set this to the format you would like to output (gif, png, jpeg)
96 *
97 * @var string
98 */
99 var $defaultOutput = 'png';
100
101 /**
102 * Contructor
103 *
104 * Pass the constructor an array and it'll use that array as its
105 * pair images. Pass it a directory and it'll parse that directory
106 * and create pairs based on the images found there.
107 *
108 * @param array|string$input
109 * @return SpriteGenerator
110 */
111 function SpriteGenerator($input = null, $match1 = '/^([a-z0-9]+)\.(jpg|jpeg|jpe|png|gif)$/i',
$match2 = '/^([a-z0-9]+)_over\.(jpg|jpeg|jpe|png|gif)$/i')
112 {
113 if (!is_null($input))
114 {
115 if (is_array($input)) $this-> _pairs = $input;
116 elseif (is_dir($input)) $this-> _parseDirectory($input, $match1, $match2);
117 else die('Unable to auto-detect ' . var_export($input, true));
118 }
119 }
120
121 /**
122 * Setter function for _pairs
123 *
124 * @param array $pairs
125 * @return boolean
126 */
127 function setPairs($pairs = array())
128 {
129 if (!is_array($pairs)) return false;
130
131 $this-> _pairs = $pairs;
132 return true;
133 }
134
135 /**
136 * Sets the directory to generate pairs from
137 *
138 * @param string $directory
139 * @return boolean
140 */
141 function setDirectory($directory, $match1 = '/^([a-z0-9]+)\.(jpg|jpeg|jpe|png|gif)$/i', $match2
= '/^([a-z0-9]+)_over\.(jpg|jpeg|jpe|png|gif)$/i')
142 {
143 if (is_dir($directory)) return $this-> _parseDirectory($input, $match1, $match2);
144 return false;

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 16 of 18
145 }
146
147 /**
148 * Parses a passed directory
149 *
150 * @param string $directory
151 */
152 function _parseDirectory($directory, $match1, $match2)
153 {
154 if (!$handle = opendir($directory)) return false;
155
156 $pairs = array();
157 while (false !== ($file = readdir($handle)))
158 {
159 if ($file == "." || $file == ".." ) continue;
160
161 if (preg_match($match1, $file, $matches)) $pairs[$matches[1]][1] = $directory . $file;
// TODO: Check for separator
162 elseif (preg_match($match2, $file, $matches)) $pairs[$matches[1]][2] = $directory .
$file;
163 }
164 closedir($handle);
165
166 foreach ($pairs as $pair)
167 $this-> _pairs[] = array($pair[1], $pair[2]);
168 }
169
170 /**
171 * Batch creates sprites for all image pairs
172 *
173 */
174 function batchSprites()
175 {
176 foreach ($this-> _pairs as $pair)
177 {
178 $image = $this-> generateSprite($pair[0], $pair[1]);
179 $this-> _writeSprite($image, $pair[0]);
180 unlink($pair[1]);
181 }
182 }
183
184 /**
185 * Generates a sprite image based on two files
186 *
187 * @param string $file1
188 * @param string $file2
189 * @return resource
190 */
191 function generateSprite($file1, $file2)
192 {
193 $image1 = $this-> _createImageFromFile($file1) or die(" Cannot open {$file1}." );
194 $image2 = $this-> _createImageFromFile($file2) or die(" Cannot open {$file2}." );
195
196 $imageWidth1 = imagesx($image1);
197 $imageWidth2 = imagesx($image2);
198
199 $imageHeight1 = imagesy($image1);
200 $imageHeight2 = imagesy($image2);
201
202 $width = ($imageWidth1 > $imageWidth2 ? $imageWidth1 : $imageWidth2);
203 $height = $imageHeight1 + $imageHeight2;
204
205 $image = @imagecreatetruecolor($width, $height) or die('Unable to create sprite.');
206 imagecopymerge($image, $image1, 0, 0, 0, 0, $imageWidth1, $imageHeight1, 100) or
die('Unable to create sprite.');
207 imagecopymerge($image, $image2, 0, $imageHeight1, 0, 0, $imageWidth2, $imageHeight2, 100)
or die('Unable to create sprite.');
208
209 imagedestroy($image1);
210 imagedestroy($image2);
211
212 return $image;
213 }
214
215 /**
216 * Internal method that creates an image resource from a file name (choosing
217 * the correct GD function based on file extension)
218 *
219 * @param string $filename
220 * @return resource

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 17 of 18
221 */
222 function _createImageFromFile($filename)
223 {
224 if (!is_readable($filename)) die(" Unable to read {$filename}" );
225
226 preg_match("|\.([a-z0-9]{2,4})$|i" , $filename, $matches);
227 $extension = $matches[1];
228 switch ($extension)
229 {
230 case 'jpg':
231 case 'jpeg':
232 case 'jpe':
233 return @imagecreatefromjpeg($filename);
234
235 case 'png':
236 return @imagecreatefrompng($filename);
237
238 case 'gif':
239 return @imagecreatefromgif($filename);
240
241 default:
242 die(" Unable to recognize {$filename}'s image type." );
243 }
244
245 return false;
246 }
247
248 /**
249 * Internal method for writing a sprite to disk
250 *
251 * @param resource $image
252 * @param string $filename
253 */
254 function _writeSprite($image, $filename)
255 {
256 $function = 'image' . $this-> defaultOutput;
257
258 if (file_exists($filename) && ! is_writable($filename)) die(" {$filename} is not
writable!" );
259 $function($image, $filename) or die (" Cannot write {$filename}" );
260 imagedestroy($image);
261 }
262 }
263
264 /*
265
266 // Example Usage:
267 $sg = new SpriteGenerator("./images/");
268 $sg->batchSprites();
269
270 */

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu


Page 18 of 18
Index

C
constructor SpriteGenerator::SpriteGenerator() 5
Contructor

R
README 11

S
SpriteGenerator::_createImageFromFile() 6
Internal method that creates an image resource from a file name (choosing
the correct GD function based on file extension)
SpriteGenerator::setPairs() 6
Setter function for _pairs
SpriteGenerator::_parseDirectory() 6
Parses a passed directory
SpriteGenerator::_writeSprite() 7
Internal method for writing a sprite to disk
SpriteGenerator.php 15
Source code
SpriteGenerator::setDirectory() 6
Sets the directory to generate pairs from
SpriteGenerator::generateSprite() 5
Generates a sprite image based on two files
SpriteGenerator 4
CSS Sprite Generator Class
SpriteGenerator::$defaultOutput 5
Set this to the format you would like to output (gif, png, jpeg)
SpriteGenerator::$_pairs 5
Internal variable to hold each pair of images to be
turned into a sprite
SpriteGenerator::batchSprites() 5
Batch creates sprites for all image pairs
SpriteGenerator.php 2
Copyright (c) 2008, Chris Morrell
All rights reserved.

Generated by phpDocumentor v1.4.0 http://www.phpdoc.org - http://pear.php.net/package/PhpDocumentor - http://www.sourceforge.net/projects/phpdocu

You might also like