You are here

function image_gd_smartcrop_crop in Smart Crop 7

Crop an image, removing the lowest entropy areas.

Parameters

array $image_data:

int $requested_x:

int $requested_y:

Return value

booleon TRUE if successful

1 call to image_gd_smartcrop_crop()
image_gd_smartcrop_scale in ./image.gd.inc
Scale and crop an image to the specified size using GD.

File

./image.gd.inc, line 39
libgd implementation of smartcrop action.

Code

function image_gd_smartcrop_crop(stdClass $image_data, $requested_x, $requested_y) {
  $image = $image_data->resource;
  $dx = imagesx($image) - min(imagesx($image), $requested_x);
  $dy = imagesy($image) - min(imagesy($image), $requested_y);
  $left = $top = 0;
  $left_entropy = $right_entropy = $top_entropy = $bottom_entropy = 0;
  $right = imagesx($image);
  $bottom = imagesy($image);

  // Slice from left and right edges until the correct width is reached.
  while ($dx) {
    $slice = min($dx, 10);

    // Calculate the entropy of the new slice.
    if (!$left_entropy) {
      $left_entropy = _smartcrop_gd_entropy_slice($image_data, $left, $top, $slice, imagesy($image));
    }
    if (!$right_entropy) {
      $right_entropy = _smartcrop_gd_entropy_slice($image_data, $right - $slice, $top, $slice, imagesy($image));
    }

    // Remove the lowest entropy slice.
    if ($left_entropy >= $right_entropy) {
      $right -= $slice;
      $right_entropy = 0;
    }
    else {
      $left += $slice;
      $left_entropy = 0;
    }
    $dx -= $slice;
  }

  // Slice from the top and bottom edges until the correct width is reached.
  while ($dy) {
    $slice = min($dy, 10);

    // Calculate the entropy of the new slice.
    if (!$top_entropy) {
      $top_entropy = _smartcrop_gd_entropy_slice($image_data, $left, $top, $requested_x, $slice);
    }
    if (!$bottom_entropy) {
      $bottom_entropy = _smartcrop_gd_entropy_slice($image_data, $left, $bottom - $slice, $requested_x, $slice);
    }

    // Remove the lowest entropy slice.
    if ($top_entropy >= $bottom_entropy) {
      $bottom -= $slice;
      $bottom_entropy = 0;
    }
    else {
      $top += $slice;
      $top_entropy = 0;
    }
    $dy -= $slice;
  }

  // Finally, crop the image using the coordinates found above.
  $cropped_image = image_gd_create_tmp($image_data, $right - $left, $bottom - $top);
  imagecopy($cropped_image, $image, 0, 0, $left, $top, $right - $left, $bottom - $top);
  imagedestroy($image_data->resource);
  $image_data->resource = $cropped_image;
  $image_data->info['width'] = $requested_x;
  $image_data->info['height'] = $requested_y;
  return TRUE;
}