1 image.gd.inc image_gd_crop(stdClass $image, $x, $y, $width, $height, $background = NULL)

Crop an image using the GD toolkit.


$image: An image object. The $image->resource, $image->info['width'], and $image->info['height'] values will be modified by this call.

$x: The starting x offset at which to start the crop, in pixels.

$y: The starting y offset at which to start the crop, in pixels.

$width: The width of the cropped area, in pixels.

$height: The height of the cropped area, in pixels.

$background: An hexadecimal integer specifying the background color to use for the uncovered area of the image after manipulation. E.g. #000000 for black, #ff00ff for magenta, and #ffffff for white. For images that support transparency, this will default to transparent. Otherwise it will be white.

Return value

TRUE or FALSE, based on success.:

See also


Related topics


core/modules/system/image.gd.inc, line 185
GD2 toolkit for image manipulation within Backdrop.


function image_gd_crop(stdClass $image, $x, $y, $width, $height, $background = NULL) {
  $width = (int) $width;
  $height = (int) $height;
  $res = image_gd_create_tmp($image, $width, $height);

  // Convert the hexadecimal background value to a color index value.
  $background = _image_gd_get_colorindex($image, $background);

  // Fill the background color.
  imagefill($res, 0, 0, $background);

  // Copy the source image to our new destination image. We use
  // $image->info['width'] instead of $width because we are copying using the
  // source image's width and height, not the destination width and height.
  if (!imagecopyresampled($res, $image->resource, -$x, -$y, 0, 0, $image->info['width'], $image->info['height'], $image->info['width'], $image->info['height'])) {
    return FALSE;

  // Destroy the original image and return the modified image.
  $image->resource = $res;
  $image->info['width'] = $width;
  $image->info['height'] = $height;
  return TRUE;