better image resizing with both fixed settings
[ouya-imagestore.git] / src / imagestore / Controller / Image.php
index f606d04979b0a2c5b82767b793a5156647216a51..c34a9d7b8a8ba26f1d7f4c454ed9ef6d123ec916 100644 (file)
@@ -14,7 +14,7 @@ class Controller_Image extends Controller_Base
             return $this->error('404 Not Found', 'File not found');
         }
         
-        if (!isset($_GET['w'])) {
+        if (!isset($_GET['w']) && !isset($_GET['h'])) {
             header('Content-type: image/jpeg');
             header('Content-length: ' . filesize($path));
             return readfile($path);
@@ -22,19 +22,39 @@ class Controller_Image extends Controller_Base
         
         //resize
         $img = imagecreatefromjpeg($path);
+        $oldX = $oldY = 0;
+        $oldW = imagesx($img);
+        $oldH = imagesy($img);
 
-        $newWidth = (int) $_GET['w'];
-        //if (isset($_GET['h'])) {
-        //    $newHeight = (int) $_GET['h'];
-        //} else {
-        $newHeight = intval($newWidth / imagesx($img) * imagesy($img));
-        //}
+        if (isset($_GET['w']) && isset($_GET['h'])) {
+            //max. bounding box respecting aspect ratio
+            $newW = (int) $_GET['w'];
+            $newH = (int) $_GET['h'];
+
+            $rW = $oldW / $newW;
+            $rH = $oldH / $newH;
+            if ($rW > $rH) {
+                $newOldW = intval($oldW / $rW * $rH);
+                $oldX = $oldW / 2 - $newOldW / 2;
+                $oldW = $newOldW;
+            } else {
+                $newOldH = intval($oldH / $rH * $rW);
+                $oldY = $oldH / 2 - $newOldH / 2;
+                $oldH = $newOldH;
+            }
+        } else if (isset($_GET['w'])) {
+            $newW = (int) $_GET['w'];
+            $newH = intval($newW / $oldW * $oldH);
+        } else {
+            $newH = (int) $_GET['h'];
+            $newW = intval($newH / $oldH * $oldW);
+        }
         
-        $thumb = imagecreatetruecolor($newWidth, $newHeight);
+        $thumb = imagecreatetruecolor($newW, $newH);
         // Resize
         imagecopyresampled(
-            $thumb, $img, 0, 0, 0, 0,
-            $newWidth, $newHeight, imagesx($img), imagesy($img)
+            $thumb, $img, 0, 0, $oldX, $oldY,
+            $newW, $newH, $oldW, $oldH
         );
         imagedestroy($img);