3 namespace Drupal\imagemagick\Plugin\ImageToolkit\Operation\imagemagick;
6 * Defines imagemagick Crop operation.
8 * @ImageToolkitOperation(
9 * id = "imagemagick_crop",
10 * toolkit = "imagemagick",
12 * label = @Translation("Crop"),
13 * description = @Translation("Crops an image to a rectangle specified by the given dimensions.")
16 class Crop extends ImagemagickImageToolkitOperationBase {
21 protected function arguments() {
24 'description' => 'The starting x offset at which to start the crop, in pixels',
27 'description' => 'The starting y offset at which to start the crop, in pixels',
30 'description' => 'The width of the cropped area, in pixels',
35 'description' => 'The height of the cropped area, in pixels',
45 protected function validateArguments(array $arguments) {
46 // Assure at least one dimension.
47 if (empty($arguments['width']) && empty($arguments['height'])) {
48 throw new \InvalidArgumentException("At least one dimension ('width' or 'height') must be provided to the image 'crop' operation");
52 $aspect = $this->getToolkit()->getHeight() / $this->getToolkit()->getWidth();
53 $arguments['height'] = empty($arguments['height']) ? $arguments['width'] * $aspect : $arguments['height'];
54 $arguments['width'] = empty($arguments['width']) ? $arguments['height'] / $aspect : $arguments['width'];
56 // Assure integers for all arguments.
57 foreach (['x', 'y', 'width', 'height'] as $key) {
58 $arguments[$key] = (int) round($arguments[$key]);
61 // Fail when width or height are 0 or negative.
62 if ($arguments['width'] <= 0) {
63 throw new \InvalidArgumentException("Invalid width ('{$arguments['width']}') specified for the image 'crop' operation");
65 if ($arguments['height'] <= 0) {
66 throw new \InvalidArgumentException("Invalid height ('{$arguments['height']}') specified for the image 'crop' operation");
75 protected function execute(array $arguments) {
76 // Even though the crop effect in Drupal core does not allow for negative
77 // offsets, ImageMagick supports them. Also note: if $x and $y are set to
78 // NULL then crop will create tiled images so we convert these to ints.
79 $this->getToolkit()->addArgument(sprintf('-crop %dx%d%+d%+d!', $arguments['width'], $arguments['height'], $arguments['x'], $arguments['y']));
80 $this->getToolkit()->setWidth($arguments['width'])->setHeight($arguments['height']);