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
<?php
/**
* Programmatically generates a gradient image.
*
* $_GET parameters:
* top The color at the top of the gradient. Specified as a 3-, 6-, or 8-digit
* hexadecimal string. For horizontal gradients, this will be the
* color on the left. The two most-significant-digits specify the 7-bit
* alpha channel, from 00 (opaque) to 7f (transparent).
* bottom The color at the bottom of the gradient. Specified as a 3-, 6-, or 8-digit
* hexadecimal string. For horizontal gradients, this will be the
* color on the right. The two most-significant-digits specify the 7-bit
* alpha channel, from 00 (opaque) to 7f (transparent).
* height The height of this gradient, in pixels. For horizontal
* gradients, this will be the width.
* orientation This should be 'h' for horizontal, 'v' for vertical. Defaults
* 'v' in the case of invalid input.
*
* define'd constants:
* CACHE_DIR The directory in which generated gradients will be stored.
* This directory must have rwx privileges.
* MAX_CACHE_SIZE The maximum disk space which will be used, in bytes, by the
* cache directory.
* WIDTH The width of the gradient. For horizontal gradients, this
* will be the height.
* MIN_HEIGHT The minimum acceptable value for $_GET['height'].
* MAX_HEIGHT The maximum acceptable value for $_GET['height'].
* ERR_DIFFUSION Whether or not to use error diffusion.
*
* @author Kip Robinson, http://www.vacant-nebula.com
*/
define('CACHE_DIR', $_SERVER['DOCUMENT_ROOT'] . '/../gradient_cache');
define('MAX_CACHE_SIZE', 5*1024*1024); //5 MB
define('WIDTH', 4);
define('MIN_HEIGHT', 4);
define('MAX_HEIGHT', 9999);
define('ERR_DIFFUSION', true);
//Validate/sanitize $_GET parameters
//---------------------------------------------------------
$top = get_color(strval($_GET['top']));
$top_hex = str_pad(dechex(intval($top)), 8, '0', STR_PAD_LEFT);
$bottom = get_color(strval($_GET['bottom']));
$bottom_hex = str_pad(dechex(intval($bottom)), 8, '0', STR_PAD_LEFT);
$is_vertical = strval($_GET['orientation']) !== 'h';
$orientation = $is_vertical ? 'v' : 'h';
$height = clamp(intval($_GET['height']), MIN_HEIGHT, MAX_HEIGHT);
//If we haven't cached this gradient, generate it.
//---------------------------------------------------------
$file = CACHE_DIR . "/$top_hex-$bottom_hex-$height-$orientation.png";
if(!file_exists($file))
{
clean_cache();
if($is_vertical)
$image = imagecreatetruecolor(WIDTH, $height);
else
$image = imagecreatetruecolor($height, WIDTH);
$top_a = ($top >> 24) & 0x7f;
$top_r = ($top >> 16) & 0xff;
$top_g = ($top >> 8) & 0xff;
$top_b = ($top ) & 0xff;
$bottom_a = ($bottom >> 24) & 0x7f;
$bottom_r = ($bottom >> 16) & 0xff;
$bottom_g = ($bottom >> 8) & 0xff;
$bottom_b = ($bottom ) & 0xff;
//Allow us to save the alpha channel if either color is not opaque.
if($top_a > 0 || $bottom_a > 0)
{
imagealphablending($image, false);
imagesavealpha($image, true);
}
//Precompute the "slope" for the interpolation function.
//Note: first row will always be $top color, and last
// row will always be $bottom color.
$m_a = ($bottom_a - $top_a) / ($height - 1.0);
$m_r = ($bottom_r - $top_r) / ($height - 1.0);
$m_g = ($bottom_g - $top_g) / ($height - 1.0);
$m_b = ($bottom_b - $top_b) / ($height - 1.0);
$err_a = 0.0;
$err_r = 0.0;
$err_g = 0.0;
$err_b = 0.0;
for($row = 0; $row < $height; $row++)
{
$act_a = $m_a * $row + $top_a;
$act_r = $m_r * $row + $top_r;
$act_g = $m_g * $row + $top_g;
$act_b = $m_b * $row + $top_b;
$a = round($act_a);
$r = round($act_r);
$g = round($act_g);
$b = round($act_b);
for($col = 0; $col < WIDTH; $col++)
{
if(ERR_DIFFUSION)
{
$err_a += $act_a - $a;
$err_r += $act_r - $r;
$err_g += $act_g - $g;
$err_b += $act_b - $b;
$cor_a = abs_floor($err_a);
$cor_r = abs_floor($err_r);
$cor_g = abs_floor($err_g);
$cor_b = abs_floor($err_b);
$err_a -= abs_floor($err_a);
$err_r -= abs_floor($err_r);
$err_g -= abs_floor($err_g);
$err_b -= abs_floor($err_b);
}
else
{
$cor_a = 0;
$cor_r = 0;
$cor_g = 0;
$cor_b = 0;
}
$color = (clamp($a + $cor_a, 0, 0x7f) << 24)
| (clamp($r + $cor_r, 0, 0xff) << 16)
| (clamp($g + $cor_g, 0, 0xff) << 8)
| (clamp($b + $cor_b, 0, 0xff) );
if($is_vertical)
imagesetpixel($image, $col, $row, $color);
else
imagesetpixel($image, $row, $col, $color);
}
}
//Write the image to the cache.
imagepng($image, $file);
imagedestroy($image);
}
//Handle If-Modified-Since header
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
$if_modified_since=strtotime(preg_replace('/;.*$/','',$_SERVER['HTTP_IF_MODIFIED_SINCE']));
if($if_modified_since !== false && $if_modified_since >= filemtime($file))
{
header('HTTP/1.1 304 Not Modified', true, 304);
exit();
}
}
//Write headers to convince browser that this is an image
//and not a web page. Use "Expires" header to let browser
//cache the image locally (it's not like it's going to change).
//---------------------------------------------------------
header('Content-type: image/png');
header('Content-Length: ' . filesize($file));
header('Pragma:'); //undo the pragma garbage PHP already wrote
header('Expires: ' . gmdate('r', mktime() + 3600*24*365));
header('Last-Modified: ' . gmdate('r', filemtime($file)));
//Finally, output the file and we're done!
//---------------------------------------------------------
readfile($file);
// ========================================================
// Helper functions
// ========================================================
/**
* Converts a 3-, 6-, or 8-digit hex string into a 32-bit int color.
*/
function get_color($strVal)
{
if(strlen($strVal) == 3)
$strVal = $strVal[0] . $strVal[0] . $strVal[1] . $strVal[1] . $strVal[2] . $strVal[2];
return clamp(hexdec(strval($strVal)), 0, 0x7fffffff);
}
/**
* Rounds $x towards zero (like floor for positive $x, ciel for negative $x).
*
* Examples:
* abs_floor(1.999) : 1
* abs_floor(1.2) : 1
* abs_floor(0.9) : 0
* abs_floor(-0.9) : 0
* abs_floor(-1.2) : -1
* abs_floor(-1.999): -1
*/
function abs_floor($x)
{
return $x < 0 ? ceil($x) : floor($x);
}
/**
* Limits $val to the range [$min..$max].
*/
function clamp($val, $min, $max)
{
if ($min > $max)
return clamp($val, $max, $min);
else if ($val < $min)
return $min;
else if ($val > $max)
return $max;
else
return $val;
}
/**
* Cleans up the cache to limit the total size of all cached gradients
* to MAX_CACHE_SIZE. Least-recently-used files will be deleted first.
* Requires execute permission on cache directory.
*/
function clean_cache()
{
$tmp_files = scandir(CACHE_DIR);
$files = array();
foreach($tmp_files as $file)
{
$path = CACHE_DIR . "/$file";
//ignore subdirectories if there are any...
if (is_file($path))
$files[] = $path;
}
unset($tmp_files);
//sort newest to oldest
usort($files, create_function('$a, $b', 'return fileatime($b)-fileatime($a);') );
//Compute the size (storage space) of cached files, starting with most recent. Once that
// size is over MAX_CACHE_SIZE, delete that file and any older files.
$cache_size = 0;
foreach($files as $file)
{
$cache_size += filesize($file);
if ($cache_size > MAX_CACHE_SIZE)
@unlink($file);
}
}