Skip to content

Commit

Permalink
CRM-20938 - Maintain aspect ratio in resizeImage()
Browse files Browse the repository at this point in the history
Make CRM_Utils_File::resizeImage() preserve image aspect ratio by
default.
  • Loading branch information
seancolsen authored and monishdeb committed Jul 24, 2017
1 parent 6c094ca commit ae969bc
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion CRM/Utils/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,11 @@ public static function getImageURL($imageURL) {
* 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
Expand All @@ -937,7 +942,7 @@ public static function getImageURL($imageURL) {
* - 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');
Expand All @@ -964,6 +969,18 @@ public static function resizeImage($sourceFile, $targetWidth, $targetHeight, $su
$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
Expand Down

0 comments on commit ae969bc

Please sign in to comment.