3 namespace Drupal\Component\Utility;
6 * Provides helpers to operate on images.
13 * Scales image dimensions while maintaining aspect ratio.
15 * The resulting dimensions can be smaller for one or both target dimensions.
17 * @param array $dimensions
18 * Dimensions to be modified - an array with components width and height, in
21 * (optional) The target width, in pixels. If this value is NULL then the
22 * scaling will be based only on the height value.
24 * (optional) The target height, in pixels. If this value is NULL then the
25 * scaling will be based only on the width value.
26 * @param bool $upscale
27 * (optional) Boolean indicating that images smaller than the target
28 * dimensions will be scaled up. This generally results in a low quality
32 * TRUE if $dimensions was modified, FALSE otherwise.
36 public static function scaleDimensions(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
37 $aspect = $dimensions['height'] / $dimensions['width'];
39 // Calculate one of the dimensions from the other target dimension,
40 // ensuring the same aspect ratio as the source dimensions. If one of the
41 // target dimensions is missing, that is the one that is calculated. If both
42 // are specified then the dimension calculated is the one that would not be
43 // calculated to be bigger than its target.
44 if (($width && !$height) || ($width && $height && $aspect < $height / $width)) {
45 $height = (int) round($width * $aspect);
48 $width = (int) round($height / $aspect);
51 // Don't upscale if the option isn't enabled.
52 if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
56 $dimensions['width'] = $width;
57 $dimensions['height'] = $height;