3 $imgpath = ltrim($Page->path, '/');
4 if (!preg_match('{^[0-9x]+/}', $imgpath)) {
7 list ($size, $imgpath) = explode('/', $imgpath, 2);
8 $imgpath = preg_replace('{^(?=[0-9]+/)}', 'data/', $imgpath, 1);
10 if (!file_exists($imgpath)) {
11 http_response_code(404);
13 if (!file_exists($imgpath)) {
19 $target = mkthumb($imgpath, $size);
21 catch (Throwable $e) {
22 http_response_code($e->getCode() ?: 500);
23 header("X-Error: ".explode("\n", $e->getMessage())[0], FALSE);
25 if (file_exists($target)) {
26 header('Content-type: '.mime_content_type($target));
30 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
34 header('Cache-Control: max-age=2628000');
35 header('Content-type: '.mime_content_type($target));
39 function mkthumb($source, $size)
41 if (strpos($size, 'x') !== FALSE) {
42 list ($width, $height) = explode('x', $size);
53 $target = "thumb/$size/$source";
55 if (isset($_GET['backend'])) {
56 $backend = $_GET['backend'];
58 elseif (file_exists($target)) {
61 elseif (extension_loaded('gd')) {
67 $backend = "mkthumb_$backend";
69 @mkdir(dirname($target), 0777, TRUE);
70 $backend($source, $target, $width, $height);
74 function mkthumb_gd($source, $target, $width, $height)
76 $data = imagecreatefromstring(file_get_contents($source));
77 if (!$data) throw new Exception("error reading $source");
78 $orgwidth = imagesx($data);
79 $orgheight = imagesy($data);
80 $width = min($width, $orgwidth * $height / $orgheight);
81 $gd = imagecreatetruecolor($width, $height);
83 imagecopyresampled($gd, $data, 0, 0, 0, 0,
84 $width, $height, $orgwidth, $orgheight);
85 imagejpeg($gd, $target, 90);
88 function mkthumb_exec($source, $target, $width, $height)
90 if (!function_exists('popen')) {
91 throw new Exception("exec disallowed on this server", 501);
93 $cmd = implode(' ', array_map('escapeshellarg', [
95 '-delete', '1--1', # static
97 '-background', 'white', '-layers', 'flatten', # opaque
98 '-auto-orient', # apply exif rotation
99 '-interlace', 'plane', # progressive
100 '-strip', '-taint', # omit metadata
101 '-sampling-factor', '4:2:0', '-colorspace', 'sRGB', # half chroma
102 '-resize', "${width}x${height}",
104 $source, "jpg:$target"
106 $return = shell_exec("$cmd 2>&1");
108 throw new Exception($return);