From 92abeb2895bb0b1e455ac045f789cb11d5227edd Mon Sep 17 00:00:00 2001 From: Christian Weiske Date: Fri, 13 Sep 2013 20:10:05 +0200 Subject: [PATCH] better image resizing with both fixed settings --- src/imagestore/Controller/Image.php | 40 +++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/src/imagestore/Controller/Image.php b/src/imagestore/Controller/Image.php index f606d04..c34a9d7 100644 --- a/src/imagestore/Controller/Image.php +++ b/src/imagestore/Controller/Image.php @@ -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); -- 2.30.2