image_scale_and_crop

Definition

image_scale_and_crop($source, $destination, $width, $height)
drupal/includes/image.inc, line 157

Description

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

Namesort iconDescription
Image toolkitsDrupal's image toolkits provide an abstraction layer for common image file manipulations like scaling, cropping, and rotating. The abstraction frees module authors from the need to support multiple image libraries, and it allows site...

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;
}