-
Notifications
You must be signed in to change notification settings - Fork 0
/
sprite.php
376 lines (308 loc) · 10.6 KB
/
sprite.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<?php
/**
* Sprite generator
*
* @author Tim Whitlock
* @license MIT
*/
require __DIR__.'/libs/php-cli/cli.php';
// dependency checks
if( ! function_exists('imagecreatetruecolor') ){
cli::death('PHP GD module required');
}
cli::register_arg( 'd', 'dir', 'Directory containing images, defaults to cwd', false );
cli::register_arg( 'w', 'width', 'Minimum width of each cell, defaults to width of image + padding', false );
cli::register_arg( '', 'height', 'Minimum height of each cell, defaults to height of image + padding', false );
cli::register_arg( 'p', 'padding','Minimum distance between items, defaults to 1', false );
cli::register_arg( 'z', 'horiz', 'Whether to lay out horizontally, defaults to vertical', false );
cli::register_arg( 'n', 'name', 'CSS class prefix and file name, defaults to "sprite"', false );
cli::register_arg( 'c', 'colour', 'Opaque background color as hex, defaults to transparent', false );
cli::register_arg( '', 'wrap', 'Wrap at this many rows (horiz) or columns (vert)', false );
cli::register_arg( 's', 'scale', 'Scaling of final images, defaults to 1', false );
cli::register_arg( 'r', 'relative', 'Whether to use relative (%) image positions', false );
cli::register_arg( 'j', 'jpeg', 'Jpeg quality to use, defaults to PNG', false );
cli::register_arg( '', 'recursive', 'Add images found in sub directories', false );
cli::validate_args();
$dir = rtrim( cli::arg('d'), "\n/") or $dir = '.';
if( ! is_readable($dir) || ! is_dir($dir) ){
throw new Exception('Directory unreadable, try with -d open_basedir='.ini_get('open_basedir').':'.$dir);
}
$prefix = cli::arg('n','sprite');
$target = $dir.'/'.$prefix;
if( $jpeg = (int) cli::arg('j') ){
$target .= '.jpg';
}
else {
$target .= '.png';
}
// configure sprite from command line flags
$Sprite = new CssSprite( cli::arg('width'), cli::arg('height'), cli::arg('horiz') );
// collect all files
if( ! $Sprite->init( $target, cli::arg('recursive') ) ){
cli::stderr("no images files found\n");
exit(1);
}
$scale = cli::arg('s') and
$Sprite->set_scale( $scale );
if( $colour = cli::arg('c') ){
$Sprite->set_colour( $colour );
}
else if( $jpeg ){
$Sprite->set_colour( '#ffffff' );
}
$wrap = cli::arg('wrap') and
$Sprite->wrap_at( $wrap );
$relative = cli::arg('r') and
$Sprite->use_relative($relative);
$padding = cli::arg('padding') and
$Sprite->pad($padding);
// export image to file
$gd = $Sprite->compile();
if( $jpeg ){
imagejpeg( $gd, $target, $jpeg );
}
else {
imagepng( $gd, $target );
}
// dump css, and tell me where the file is
echo "/* sprite saved to ",$target," */\n";
foreach( $Sprite->get_css($prefix) as $line ){
echo $line,"\n";
}
//
class CssSprite {
// config
private $horiz;
private $padding = 1;
private $minwidth;
private $minheight;
private $wrapnum;
private $_scale;
private $colour = array( 0xFF, 0xFF, 0xFF, 127 );
private $relative = false;
// grid [ [ { x:, y: }, {} ], [ {} ] ]
private $x = 0;
private $y = 0;
private $rows = array();
private $r = 0;
private $c = 0;
// max bounds
private $width = 0;
private $height = 0;
// file system
private $basedir;
private $target;
public function __construct( $minwidth = 0, $minheight = 0, $horiz = false ){
$this->minwidth = (int) $minwidth;
$this->minheight = (int) $minheight;
$this->horiz = (bool) $horiz;
}
public function init( $target, $recursive = false ){
$this->target = $target;
$this->basedir = dirname($target);
return $this->find( $this->basedir, $recursive );
}
private function find( $dir, $recursive ){
$n = 0;
// files
foreach( glob( $dir.'/*.{png,jpeg,jpg,gif}', GLOB_BRACE|GLOB_NOSORT) as $f ){
if( $f === $this->target ){
continue; // <- previously saved sprite
}
$this->add_file( $f );
$n++;
}
// folders:
if( $recursive ){
foreach( glob( $dir.'/*', GLOB_ONLYDIR|GLOB_NOSORT ) as $d ){
$n += $this->find( $d, true );
}
}
return $n;
}
private function add_file( $path ){
$inf = getimagesize( $path );
if( ! $inf || ! $inf[2] ){
throw new Exception('Invalid image file '.$path);
}
list( $width, $height, $type ) = $inf;
// convert file name in to css name
$name = substr( $path, 1 + strlen($this->basedir) );
$name = preg_replace('/\.[a-z]+$/i', '', $name );
$name = strtr( $name, '/', '-' );
// register this cell at current point the grid
$this->rows[$this->r][$this->c] = array (
'w' => $width,
'h' => $height,
't' => $type,
'x' => $this->x,
'y' => $this->y,
'p' => $path,
'n' => $name,
);
// increase bounds by minimum amount
$this->width = max( $this->width, $this->x + $width );
$this->height = max( $this->height, $this->y + $height );
// set grid space for this item
$width += $this->padding;
$width = $this->minwidth ? max( $this->minwidth, $width ) : $width;
$height += $this->padding;
$height = $this->minheight ? max( $this->minheight, $height ) : $height;
// move grid position ready for next item
if( $this->horiz ){
// wrap to next row?
if( ++$this->c === $this->wrapnum ){
$this->c = $this->x = 0;
$this->r++;
$this->y+= $height;
}
// no, increment to next column
else {
$this->x += $width;
}
}
// wrap to top of next column?
else if( ++$this->r === $this->wrapnum ){
$this->c++;
$this->x += $width;
$this->r = $this->y = 0;
}
// no, increment to next row
else {
$this->y += $height;
}
return $this;
}
/**
*
*/
public function pad( $px ){
$this->padding = (int) $px;
}
/**
*
*/
public function wrap_at( $col_or_row = null ){
$was = $this->wrapnum;
if( isset($col_or_row) ){
$this->wrapnum = (int) $col_or_row;
}
return $was;
}
/**
*
*/
public function use_relative( $bool = null ){
$was = $this->relative;
if( isset($bool) ){
if( $bool ){
if( ! $this->minwidth && ( $this->horiz || $this->wrapnum ) ){
throw new Exception('relative horizontal offsets require width setting');
}
if( ! $this->minheight && ( ! $this->horiz || $this->wrapnum ) ){
throw new Exception('relative vertical offsets require height setting');
}
}
$this->relative = (bool) $bool;
}
return $was;
}
/**
*
*/
public function set_scale( $scale ){
$this->_scale = 1;
if( $scale && '1' !== $scale ){
$scale = floatval($scale) and
$this->_scale = $scale;
}
// ensure padding is not scaled
$this->padding = (int) ceil( $this->padding / $this->_scale );
return $this->_scale;
}
/**
*
*/
private function scale( $n ){
if( ! $n ){
return 0;
}
if( $this->_scale && 1 !== $this->_scale ){
$n = (int) ceil( $this->_scale * $n );
}
return $n;
}
/**
*
*/
public function get_css( $prefix = 'sprite' ){
$w = $this->minwidth ? $this->scale($this->minwidth) : 0;
$h = $this->minheight ? $this->scale($this->minheight) : 0;
if( $this->relative ){
// background %age subtracts visible area from 100% so be sure to set --width and --height
$ww = $this->scale( $this->width - $w );
$hh = $this->scale( $this->height - $h );
}
$lines[] = sprintf(
'.%s { background: url(%1$s.png) no-repeat; display: inline-block; min-width: %upx; min-height: %upx; }',
$prefix, $w, $h
);
foreach( $this->rows as $row ){
foreach( $row as $cell ){
extract( $cell );
$x = $this->scale($x);
$y = $this->scale($y);
if( $this->relative ){
$x = $x ? ( $x === $ww ? 'right' : sprintf( '%f%%', 100 * $x / $ww ) ) : '0';
$y = $y ? ( $y === $hh ? 'bottom' : sprintf( '%f%%', 100 * $y / $hh ) ) : '0';
}
else {
$x = $x ? '-'.$x.'px' : '0';
$y = $y ? '-'.$y.'px' : '0';
}
$lines[] = sprintf( '.%s-%s { background-position: %s %s; }', $prefix, $n, $x, $y);
}
}
return $lines;
}
/**
* @todo handle alpha RRGGBBAA
*/
public function set_colour( $colour ){
if( ! is_array($colour) ){
$n = intval( trim($colour,' #'), 16 );
$colour = array( $n & 0xFF );
array_unshift( $colour, ($n>>=8) & 0xFF );
array_unshift( $colour, ($n>>=8) & 0xFF );
}
$this->colour = $colour + array(127,127,127,0);
}
/**
* Build final sprite image
* @return resource GD image handle
*/
public function compile(){
$w = $this->scale( $this->width );
$h = $this->scale( $this->height );
// create transparent canvas to start
$sprite = imagecreatetruecolor( $w, $h );
imagesavealpha( $sprite, true );
imagefill( $sprite, 0, 0, imagecolorallocatealpha( $sprite, $this->colour[0], $this->colour[1], $this->colour[2], $this->colour[3] ) );
// superimpose all image files
foreach( $this->rows as $row ){
foreach( $row as $cell ){
extract( $cell, EXTR_PREFIX_ALL, 'src' );
extract( $cell, EXTR_PREFIX_ALL, 'dst' );
$gd = imagecreatefromstring( file_get_contents($src_p) );
$dst_x = $this->scale($dst_x);
$dst_y = $this->scale($dst_y);
$dst_w = $this->scale($dst_w);
$dst_h = $this->scale($dst_h);
if( ! imagecopyresampled( $sprite, $gd, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $src_w, $src_h ) ){
throw new Exception('Failed to composite '.$p);
}
}
}
return $sprite;
}
}