3 namespace Drupal\imagemagick\Plugin\ImageToolkit\Operation\imagemagick;
5 use Drupal\Component\Utility\Color;
6 use Drupal\Component\Utility\Rectangle;
9 * Defines imagemagick Rotate operation.
11 * @ImageToolkitOperation(
12 * id = "imagemagick_rotate",
13 * toolkit = "imagemagick",
14 * operation = "rotate",
15 * label = @Translation("Rotate"),
16 * description = @Translation("Rotates an image by the given number of degrees.")
19 class Rotate extends ImagemagickImageToolkitOperationBase {
24 protected function arguments() {
27 'description' => 'The number of (clockwise) degrees to rotate the image',
30 'description' => "A string specifying the hexadecimal color code to use as background for the uncovered area of the image after the rotation. E.g. '#000000' for black, '#ff00ff' for magenta, and '#ffffff' for white. For images that support transparency, this will default to transparent white",
35 'description' => 'An optional filter to apply for the resize',
45 protected function validateArguments(array $arguments) {
46 // Validate or set background color argument.
47 if (!empty($arguments['background'])) {
48 // Validate the background color.
49 if (!Color::validateHex($arguments['background'])) {
50 throw new \InvalidArgumentException("Invalid color '{$arguments['background']}' specified for the 'rotate' operation.");
54 // Background color is not specified: use transparent.
55 $arguments['background'] = 'transparent';
63 protected function execute(array $arguments) {
65 $arg = '-background ' . $this->getToolkit()->escapeShellArg($arguments['background']);
66 $arg .= ' -rotate ' . $arguments['degrees'];
68 $this->getToolkit()->addArgument($arg);
70 // Need to resize the image after rotation to make sure it complies with
71 // the dimensions expected, calculated via the Rectangle class.
72 $box = new Rectangle($this->getToolkit()->getWidth(), $this->getToolkit()->getHeight());
73 $box = $box->rotate((float) $arguments['degrees']);
74 return $this->getToolkit()->apply('resize', ['width' => $box->getBoundingWidth(), 'height' => $box->getBoundingHeight(), 'filter' => $arguments['resize_filter']]);