thumb: catch php errors during (gd) resize
[minimedit.git] / thumb / index.php
index 2849bb50d59f689bfdc927a34ae0b1eb04938f34..1d369488c927b78399d9a2e208559286a109c595 100644 (file)
@@ -16,7 +16,7 @@ if (!file_exists($imgpath)) {
 try {
        $target = mkthumb($imgpath, $width, $height);
 }
-catch (Exception $e) {
+catch (Throwable $e) {
        http_response_code($e->getCode() ?: 500);
        $target = '500.png';
        if (file_exists($target)) {
@@ -43,6 +43,9 @@ function mkthumb($source, $width, $height)
        elseif (file_exists($target)) {
                return;
        }
+       elseif (extension_loaded('gd')) {
+               $backend = 'gd';
+       }
        else {
                $backend = 'exec';
        }
@@ -53,6 +56,20 @@ function mkthumb($source, $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)
 {
        if (!function_exists('popen')) {