From 78e8418d39975e22043b3ffe1df04a439c9ee25c Mon Sep 17 00:00:00 2001 From: deva Date: Fri, 16 Apr 2010 17:58:50 +0000 Subject: New improved scaling (and now cutting) function. --- utils/imagecache.php | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/utils/imagecache.php b/utils/imagecache.php index 347e946..3f91d79 100644 --- a/utils/imagecache.php +++ b/utils/imagecache.php @@ -15,19 +15,33 @@ class ImageSize { } }; -function rescale($image, $maxwidth, $maxheight) +function rescale($image, $width, $height) { - $width = imagesx($image); - $height = imagesy($image); - - if($width <= $maxwidth && $height <= $maxheight) return $image; - - $scale = 1; - if($width > $maxwidth) $scale = $width / $maxwidth; - if($height / $scale > $maxheight) $scale = $height / $maxheight; - - $image_p = imagecreatetruecolor($width / $scale, $height / $scale); - imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width / $scale, $height / $scale, $width, $height); + $aspect = $width / $height; + + $w = imagesx($image); + $h = imagesy($image); + + $image_p = imagecreatetruecolor($width, $height); + + $margin = 0; + $scale = 1.0; + + if($w / $h > $aspect) { + // Cut right and left sides + $scale = $height / $h; + $margin = ($w * $scale - $width) / 2; + $margin /= $scale; + imagecopyresampled($image_p, $image, 0, 0, 0 + $margin, 0, + $width, $height, $w - $margin * 2, $h); + } else { + // Cut top and bottom + $scale = $width / $w; + $margin = ($h * $scale - $height) / 2; + $margin /= $scale; + imagecopyresampled($image_p, $image, 0, 0, 0, 0 + $margin / 2, + $width, $height, $w, $h - $margin * 2); + } return $image_p; } -- cgit v1.2.3