thumb: output results of existing target
[minimedit.git] / thumb / index.php
index 1267919810daf320bbb9e00b9b9e2afd66d5674d..d662b5ffa2f26a29cd4620f294e56c11fddaff40 100644 (file)
@@ -13,11 +13,10 @@ if (!file_exists($imgpath)) {
        }
 }
 
-$target = "thumb/$height/$imgpath";
 try {
-       mkthumb($imgpath, $target, $width, $height);
+       $target = mkthumb($imgpath, $width, $height);
 }
-catch (Exception $e) {
+catch (Throwable $e) {
        http_response_code($e->getCode() ?: 500);
        $target = '500.png';
        if (file_exists($target)) {
@@ -34,13 +33,18 @@ header('Content-type: '.mime_content_type($target));
 readfile($target);
 exit;
 
-function mkthumb($source, $target, $width, $height)
+function mkthumb($source, $width, $height)
 {
+       $target = "thumb/$height/$source";
+
        if (isset($_GET['backend'])) {
                $backend = $_GET['backend'];
        }
        elseif (file_exists($target)) {
-               return;
+               return $target;
+       }
+       elseif (extension_loaded('gd')) {
+               $backend = 'gd';
        }
        else {
                $backend = 'exec';
@@ -49,6 +53,21 @@ function mkthumb($source, $target, $width, $height)
 
        @mkdir(dirname($target), 0777, TRUE);
        $backend($source, $target, $width, $height);
+       return $target;
+}
+
+function mkthumb_gd($source, $target, $width, $height)
+{
+       $data = imagecreatefromstring(file_get_contents($source));
+       if (!$data) throw new Exception("error reading $source");
+       $orgwidth = imagesx($data);
+       $orgheight = imagesy($data);
+       $width = min($width, $orgwidth * $height / $orgheight);
+       $gd = imagecreatetruecolor($width, $height);
+       //TODO: trim
+       imagecopyresampled($gd, $data, 0, 0, 0, 0,
+                       $width, $height, $orgwidth, $orgheight);
+       imagejpeg($gd, $target, 90);
 }
 
 function mkthumb_exec($source, $target, $width, $height)