From ae969bc19ef7b31eb472f9fb0e7e2e9bc8275e14 Mon Sep 17 00:00:00 2001 From: Sean Madsen Date: Fri, 21 Jul 2017 11:01:39 -0600 Subject: [PATCH] CRM-20938 - Maintain aspect ratio in resizeImage() Make CRM_Utils_File::resizeImage() preserve image aspect ratio by default. --- CRM/Utils/File.php | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/CRM/Utils/File.php b/CRM/Utils/File.php index 3c3ae27b15..2ac57eb3b8 100644 --- a/CRM/Utils/File.php +++ b/CRM/Utils/File.php @@ -929,6 +929,11 @@ HTACCESS; * If supplied, the image will be renamed to include this suffix. For * example if the original file name is "foo.png" and $suffix = "_bar", * then the final file name will be "foo_bar.png". + * @param bool $preserveAspect = TRUE + * When TRUE $width and $height will be used as a bounding box, outside of + * which the resized image will not extend. + * When FALSE, the image will be resized exactly to $width and $height, even + * if it means stretching it. * * @return string * Path to image @@ -937,7 +942,7 @@ HTACCESS; * - When GD is not available. * - When the source file is not an image. */ - public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "") { + public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $suffix = "", $preserveAspect = TRUE) { // Check if GD is installed $gdSupport = CRM_Utils_System::getModuleSetting('gd', 'GD Support'); @@ -964,6 +969,18 @@ HTACCESS; $sourceWidth = $sourceInfo[0]; $sourceHeight = $sourceInfo[1]; + // Adjust target width/height if preserving aspect ratio + if ($preserveAspect) { + $sourceAspect = $sourceWidth / $sourceHeight; + $targetAspect = $targetWidth / $targetHeight; + if ($sourceAspect > $targetAspect) { + $targetHeight = $targetWidth / $sourceAspect; + } + if ($sourceAspect < $targetAspect) { + $targetWidth = $targetHeight * $sourceAspect; + } + } + // figure out the new filename $pathParts = pathinfo($sourceFile); $targetFile = $pathParts['dirname'] . DIRECTORY_SEPARATOR -- 2.25.1