3 namespace Drupal\system\Plugin\ImageToolkit\Operation\gd;
6 * Defines GD2 Crop operation.
8 * @ImageToolkitOperation(
12 * label = @Translation("Crop"),
13 * description = @Translation("Crops an image to a rectangle specified by the given dimensions.")
16 class Crop extends GDImageToolkitOperationBase {
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 // Create a new resource of the required dimensions, and copy and resize
77 // the original resource on it with resampling. Destroy the original
78 // resource upon success.
79 $original_resource = $this->getToolkit()->getResource();
81 'width' => $arguments['width'],
82 'height' => $arguments['height'],
83 'extension' => image_type_to_extension($this->getToolkit()->getType(), FALSE),
84 'transparent_color' => $this->getToolkit()->getTransparentColor(),
87 if ($this->getToolkit()->apply('create_new', $data)) {
88 if (imagecopyresampled($this->getToolkit()->getResource(), $original_resource, 0, 0, $arguments['x'], $arguments['y'], $arguments['width'], $arguments['height'], $arguments['width'], $arguments['height'])) {
89 imagedestroy($original_resource);
93 // In case of failure, destroy the temporary resource and restore
95 imagedestroy($this->getToolkit()->getResource());
96 $this->getToolkit()->setResource($original_resource);