1 image.inc image_scale_and_crop(stdClass $image, $width, $height, $anchor = 'center-center')

Scales an image to the exact width and height given.

This function achieves the target aspect ratio by cropping the original image according to the selected anchor type.

The resulting image always has the exact target dimensions.

@since 1.21.0 $anchor parameter added.

Parameters

$image: An image object returned by image_load().

$width: The target width, in pixels.

$height: The target height, in pixels.

$anchor: The anchor to use when cropping.

Return value

TRUE on success, FALSE on failure.:

See also

image_load()

image_resize()

image_crop()

image_scale_and_crop_effect()

Related topics

File

core/includes/image.inc, line 221
API for manipulating images.

Code

function image_scale_and_crop(stdClass $image, $width, $height, $anchor = 'center-center') {
  $scale = max($width / $image->info['width'], $height / $image->info['height']);

  // Set the top left coordinates of the crop area, based on the anchor.
  list($x, $y) = explode('-', $anchor);
  $x = image_filter_keyword($x, $image->info['width'] * $scale, $width);
  $y = image_filter_keyword($y, $image->info['height'] * $scale, $height);

  if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) {
    return image_crop($image, $x, $y, $width, $height);
  }
  return FALSE;
}