2 list ($size, $imgpath) = explode('/', ltrim($Args, '/'), 2);
3 $imgpath = preg_replace('{^(?=[0-9]+/)}', 'data/', $imgpath, 1);
5 if (!file_exists($imgpath)) {
6 http_response_code(404);
8 if (!file_exists($imgpath)) {
14 $target = mkthumb($imgpath, $size);
16 catch (Throwable $e) {
17 http_response_code($e->getCode() ?: 500);
18 header("X-Error: ".explode("\n", $e->getMessage())[0], FALSE);
20 if (file_exists($target)) {
21 header('Content-type: '.mime_content_type($target));
25 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
29 header('Cache-Control: max-age=2628000');
30 header('Content-type: '.mime_content_type($target));
34 function mkthumb($source, $size)
36 if (strpos($size, 'x') !== FALSE) {
37 list ($width, $height) = explode('x', $size);
48 $target = "thumb/$size/$source";
50 if (isset($_GET['backend'])) {
51 $backend = $_GET['backend'];
53 elseif (file_exists($target)) {
56 elseif (extension_loaded('gd')) {
62 $backend = "mkthumb_$backend";
64 @mkdir(dirname($target), 0777, TRUE);
65 $backend($source, $target, $width, $height);
69 function mkthumb_gd($source, $target, $width, $height)
71 $data = imagecreatefromstring(file_get_contents($source));
72 if (!$data) throw new Exception("error reading $source");
73 $orgwidth = imagesx($data);
74 $orgheight = imagesy($data);
75 $width = min($width, $orgwidth * $height / $orgheight);
76 $gd = imagecreatetruecolor($width, $height);
78 imagecopyresampled($gd, $data, 0, 0, 0, 0,
79 $width, $height, $orgwidth, $orgheight);
80 imagejpeg($gd, $target, 90);
83 function mkthumb_exec($source, $target, $width, $height)
85 if (!function_exists('popen')) {
86 throw new Exception("exec disallowed on this server", 501);
88 $cmd = implode(' ', array_map('escapeshellarg', [
90 '-delete', '1--1', # static
92 '-background', 'white', '-layers', 'flatten', # opaque
93 '-interlace', 'plane', # progressive
94 '-strip', '-taint', # omit metadata
95 '-sampling-factor', '4:2:0', '-colorspace', 'sRGB', # half chroma
96 '-resize', "${width}x${height}",
98 $source, "jpg:$target"
100 $return = shell_exec("$cmd 2>&1");
102 throw new Exception($return);