Same name and namespace in other branches
  1. 7.x includes/image.inc \image_scale_and_crop()

Scales an image to the exact width and height given. Achieves the target aspect ratio by cropping the original image equally on both sides, or equally on the top and bottom. This function is, for example, useful to create uniform sized avatars from larger images.

The resulting image always has the exact target dimensions.

Parameters

$source: The file path of the source image.

$destination: The file path of the destination image.

$width: The target width, in pixels.

$height: The target height, in pixels.

Return value

TRUE or FALSE, based on success.

Related topics

File

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

Code

function image_scale_and_crop($source, $destination, $width, $height) {
  $info = image_get_info($source);
  $scale = max($width / $info['width'], $height / $info['height']);
  $x = round(($info['width'] * $scale - $width) / 2);
  $y = round(($info['height'] * $scale - $height) / 2);
  if (image_toolkit_invoke('resize', array(
    $source,
    $destination,
    $info['width'] * $scale,
    $info['height'] * $scale,
  ))) {
    return image_toolkit_invoke('crop', array(
      $destination,
      $destination,
      $x,
      $y,
      $width,
      $height,
    ));
  }
  return FALSE;
}