You are here

function image_dimensions_scale in Drupal 7

Scales image dimensions while maintaining aspect ratio.

The resulting dimensions can be smaller for one or both target dimensions.

Parameters

$dimensions: Dimensions to be modified - an array with components width and height, in pixels.

$width: The target width, in pixels. If this value is NULL then the scaling will be based only on the height value.

$height: The target height, in pixels. If this value is NULL then the scaling will be based only on the width value.

$upscale: Boolean indicating that images smaller than the target dimensions will be scaled up. This generally results in a low quality image.

Return value

TRUE if $dimensions was modified, FALSE otherwise.

See also

image_scale()

Related topics

3 calls to image_dimensions_scale()
ImageDimensionsScaleTestCase::testImageDimensionsScale in modules/image/image.test
Tests all control flow branches in image_dimensions_scale().
image_scale in includes/image.inc
Scales an image while maintaining aspect ratio.
image_scale_dimensions in modules/image/image.effects.inc
Image dimensions callback; Scale.

File

includes/image.inc, line 203
API for manipulating images.

Code

function image_dimensions_scale(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
  $aspect = $dimensions['height'] / $dimensions['width'];

  // Calculate one of the dimensions from the other target dimension,
  // ensuring the same aspect ratio as the source dimensions. If one of the
  // target dimensions is missing, that is the one that is calculated. If both
  // are specified then the dimension calculated is the one that would not be
  // calculated to be bigger than its target.
  if ($width && !$height || $width && $height && $aspect < $height / $width) {
    $height = (int) round($width * $aspect);
  }
  else {
    $width = (int) round($height / $aspect);
  }

  // Don't upscale if the option isn't enabled.
  if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
    return FALSE;
  }
  $dimensions['width'] = $width;
  $dimensions['height'] = $height;
  return TRUE;
}