4 list ($size, $imgpath) = explode('/', ltrim($Args, '/'), 2);
5 $imgpath = preg_replace('{^(?=[0-9]+/)}', 'data/', $imgpath, 1);
7 if (!file_exists($imgpath)) {
8 http_response_code(404);
10 if (!file_exists($imgpath)) {
16 $target = mkthumb($imgpath, $size);
18 catch (Throwable $e) {
19 http_response_code($e->getCode() ?: 500);
20 header("X-Error: ".explode("\n", $e->getMessage())[0], FALSE);
22 if (file_exists($target)) {
23 header('Content-type: '.mime_content_type($target));
27 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
31 header('Cache-Control: max-age=2628000, immutable');
32 header('Content-type: '.mime_content_type($target));
36 function mkthumb($source, $size)
38 if (strpos($size, 'x') !== FALSE) {
39 list ($width, $height) = explode('x', $size);
50 $target = "thumb/$size/$source";
52 if (isset($_GET['backend'])) {
53 $backend = $_GET['backend'];
55 elseif (file_exists($target)) {
58 elseif (extension_loaded('gd')) {
64 $backend = "mkthumb_$backend";
66 @mkdir(dirname($target), 0777, TRUE);
67 $backend($source, $target, $width, $height);
71 function mkthumb_gd($source, $target, $width, $height)
73 $data = imagecreatefromstring(file_get_contents($source));
74 if (!$data) throw new Exception("error reading $source");
75 $orgwidth = imagesx($data);
76 $orgheight = imagesy($data);
77 $width = min($width, $orgwidth * $height / $orgheight);
78 $gd = imagecreatetruecolor($width, $height);
80 imagecopyresampled($gd, $data, 0, 0, 0, 0,
81 $width, $height, $orgwidth, $orgheight);
82 imagejpeg($gd, $target, 90);
85 function mkthumb_exec($source, $target, $width, $height)
87 if (!function_exists('popen')) {
88 throw new Exception("exec disallowed on this server", 501);
90 $cmd = implode(' ', array_map('escapeshellarg', [
93 '-background', 'white', '-layers', 'flatten',
94 '-resize', "${width}x${height}",
96 $source, "jpg:$target"
98 $return = shell_exec("$cmd 2>&1");
100 throw new Exception($return);