You are here

function image_imagick_smartcrop_crop in Imagick 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_imagick_smartcrop_crop()
image_imagick_smartcrop_scale in imagick_smartcrop/imagick_smartcrop.inc
Scale and crop an image to the specified size using Imagemagick.

File

imagick_smartcrop/imagick_smartcrop.inc, line 31

Code

function image_imagick_smartcrop_crop(stdClass $image_data, $requested_x, $requested_y) {
  $sx = $image_data->info['width'];
  $sy = $image_data->info['height'];
  $dx = $sx - min($sx, $requested_x);
  $dy = $sy - min($sy, $requested_y);
  $left = $top = 0;
  $left_entropy = $right_entropy = $top_entropy = $bottom_entropy = 0;
  $right = $sx;
  $bottom = $sy;

  // 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_imagick_entropy_slice($image_data, $left, $top, $slice, $sy);
    }
    if (!$right_entropy) {
      $right_entropy = _smartcrop_imagick_entropy_slice($image_data, $right - $slice, $top, $slice, $sy);
    }

    // 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_imagick_entropy_slice($image_data, $left, $top, $requested_x, $slice);
    }
    if (!$bottom_entropy) {
      $bottom_entropy = _smartcrop_imagick_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.
  return image_imagick_crop($image_data, $left, $top, $right - $left, $bottom - $top);
}