3 list ($size, $imgpath) = explode('/', ltrim($Page->path, '/'), 2);
4 $imgpath = preg_replace('{^(?=[0-9]+/)}', 'data/', $imgpath, 1);
6 if (!file_exists($imgpath)) {
7 http_response_code(404);
9 if (!file_exists($imgpath)) {
15 $target = mkthumb($imgpath, $size);
17 catch (Throwable $e) {
18 http_response_code($e->getCode() ?: 500);
19 header("X-Error: ".explode("\n", $e->getMessage())[0], FALSE);
21 if (file_exists($target)) {
22 header('Content-type: '.mime_content_type($target));
26 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
30 header('Cache-Control: max-age=2628000');
31 header('Content-type: '.mime_content_type($target));
35 function mkthumb($source, $size)
37 if (strpos($size, 'x') !== FALSE) {
38 list ($width, $height) = explode('x', $size);
49 $target = "thumb/$size/$source";
51 if (isset($_GET['backend'])) {
52 $backend = $_GET['backend'];
54 elseif (file_exists($target)) {
57 elseif (extension_loaded('gd')) {
63 $backend = "mkthumb_$backend";
65 @mkdir(dirname($target), 0777, TRUE);
66 $backend($source, $target, $width, $height);
70 function mkthumb_gd($source, $target, $width, $height)
72 $data = imagecreatefromstring(file_get_contents($source));
73 if (!$data) throw new Exception("error reading $source");
74 $orgwidth = imagesx($data);
75 $orgheight = imagesy($data);
76 $width = min($width, $orgwidth * $height / $orgheight);
77 $gd = imagecreatetruecolor($width, $height);
79 imagecopyresampled($gd, $data, 0, 0, 0, 0,
80 $width, $height, $orgwidth, $orgheight);
81 imagejpeg($gd, $target, 90);
84 function mkthumb_exec($source, $target, $width, $height)
86 if (!function_exists('popen')) {
87 throw new Exception("exec disallowed on this server", 501);
89 $cmd = implode(' ', array_map('escapeshellarg', [
91 '-delete', '1--1', # static
93 '-background', 'white', '-layers', 'flatten', # opaque
94 '-auto-orient', # apply exif rotation
95 '-interlace', 'plane', # progressive
96 '-strip', '-taint', # omit metadata
97 '-sampling-factor', '4:2:0', '-colorspace', 'sRGB', # half chroma
98 '-resize', "${width}x${height}",
100 $source, "jpg:$target"
102 $return = shell_exec("$cmd 2>&1");
104 throw new Exception($return);