thumb: move imagemagick execution to separate function
[minimedit.git] / thumb / index.php
1 <?php
2 ob_clean();
3
4 list ($height, $imgpath) = explode('/', ltrim($Args, '/'), 2);
5 $width= 1000;
6 $imgpath = preg_replace('{^(?=[0-9]+/)}', 'data/', $imgpath, 1);
7
8 if (!function_exists('popen')) {
9         http_response_code(501);
10         $target = '501.png';
11         header('Content-type: '.mime_content_type($target));
12         readfile($target);
13         exit;
14 }
15
16 if (!file_exists($imgpath)) {
17         http_response_code(404);
18         exit;
19 }
20
21 $target = "thumb/$height/$imgpath";
22 if (!file_exists($target)) {
23         try {
24                 mkthumb($imgpath, $target, $width, $height);
25         }
26         catch (Exception $e) {
27                 http_response_code(500);
28                 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
29                 exit;
30         }
31 }
32
33 header('Content-type: '.mime_content_type($target));
34 readfile($target);
35 exit;
36
37 function mkthumb($source, $target, $width, $height)
38 {
39         @mkdir(dirname($target), 0777, TRUE);
40         return mkthumb_exec($source, $target, $width, $height);
41 }
42
43 function mkthumb_exec($source, $target, $width, $height)
44 {
45         $cmd = implode(' ', array_map('escapeshellarg', [
46                 'convert',
47                 '-trim',
48                 '-resize', "${width}x${height}",
49                 '-quality', '90%',
50                 $source, $target
51         ]));
52         $return = shell_exec("$cmd 2>&1");
53         if ($return) {
54                 throw new Exception($return);
55         }
56 }