thumb: prefer native GD over external convert
[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 (!file_exists($imgpath)) {
9         http_response_code(404);
10         $imgpath = '404.png';
11         if (!file_exists($imgpath)) {
12                 exit;
13         }
14 }
15
16 try {
17         $target = mkthumb($imgpath, $width, $height);
18 }
19 catch (Exception $e) {
20         http_response_code($e->getCode() ?: 500);
21         $target = '500.png';
22         if (file_exists($target)) {
23                 header("X-Error: ".$e->getMessage());
24                 header('Content-type: '.mime_content_type($target));
25                 readfile($target);
26                 exit;
27         }
28         trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
29         exit;
30 }
31
32 header('Content-type: '.mime_content_type($target));
33 readfile($target);
34 exit;
35
36 function mkthumb($source, $width, $height)
37 {
38         $target = "thumb/$height/$source";
39
40         if (isset($_GET['backend'])) {
41                 $backend = $_GET['backend'];
42         }
43         elseif (file_exists($target)) {
44                 return;
45         }
46         elseif (extension_loaded('gd')) {
47                 $backend = 'gd';
48         }
49         else {
50                 $backend = 'exec';
51         }
52         $backend = "mkthumb_$backend";
53
54         @mkdir(dirname($target), 0777, TRUE);
55         $backend($source, $target, $width, $height);
56         return $target;
57 }
58
59 function mkthumb_gd($source, $target, $width, $height)
60 {
61         $data = imagecreatefromstring(file_get_contents($source));
62         if (!$data) throw new Exception("error reading $source");
63         $orgwidth = imagesx($data);
64         $orgheight = imagesy($data);
65         $width = min($width, $orgwidth * $height / $orgheight);
66         $gd = imagecreatetruecolor($width, $height);
67         //TODO: trim
68         imagecopyresampled($gd, $data, 0, 0, 0, 0,
69                         $width, $height, $orgwidth, $orgheight);
70         imagejpeg($gd, $target, 90);
71 }
72
73 function mkthumb_exec($source, $target, $width, $height)
74 {
75         if (!function_exists('popen')) {
76                 throw new Exception("exec disallowed on this server", 501);
77         }
78         $cmd = implode(' ', array_map('escapeshellarg', [
79                 'convert',
80                 '-trim',
81                 '-resize', "${width}x${height}",
82                 '-quality', '90%',
83                 $source, $target
84         ]));
85         $return = shell_exec("$cmd 2>&1");
86         if ($return) {
87                 throw new Exception($return);
88         }
89 }