3 namespace Drupal\imagemagick\Plugin\ImageToolkit\Operation\imagemagick;
5 use Drupal\Component\Utility\Color;
8 * Defines imagemagick CreateNew operation.
10 * @ImageToolkitOperation(
11 * id = "imagemagick_create_new",
12 * toolkit = "imagemagick",
13 * operation = "create_new",
14 * label = @Translation("Set a new image"),
15 * description = @Translation("Creates a new transparent resource and sets it for the image.")
18 class CreateNew extends ImagemagickImageToolkitOperationBase {
23 protected function arguments() {
26 'description' => 'The width of the image, in pixels',
29 'description' => 'The height of the image, in pixels',
32 'description' => 'The extension of the image file (e.g. png, gif, etc.)',
36 'transparent_color' => [
37 'description' => 'The RGB hex color for GIF transparency',
39 'default' => '#ffffff',
47 protected function validateArguments(array $arguments) {
48 // Assure extension is supported.
49 if (!in_array($arguments['extension'], $this->getToolkit()->getSupportedExtensions())) {
50 throw new \InvalidArgumentException("Invalid extension ('{$arguments['extension']}') specified for the image 'create_new' operation");
53 // Assure integers for width and height.
54 $arguments['width'] = (int) round($arguments['width']);
55 $arguments['height'] = (int) round($arguments['height']);
57 // Fail when width or height are 0 or negative.
58 if ($arguments['width'] <= 0) {
59 throw new \InvalidArgumentException("Invalid width ('{$arguments['width']}') specified for the image 'create_new' operation");
61 if ($arguments['height'] <= 0) {
62 throw new \InvalidArgumentException("Invalid height ({$arguments['height']}) specified for the image 'create_new' operation");
65 // Assure transparent color is a valid hex string.
66 if ($arguments['transparent_color'] && !Color::validateHex($arguments['transparent_color'])) {
67 throw new \InvalidArgumentException("Invalid transparent color ({$arguments['transparent_color']}) specified for the image 'create_new' operation");
76 protected function execute(array $arguments) {
78 ->setWidth($arguments['width'])
79 ->setHeight($arguments['height'])
80 ->setExifOrientation(NULL)
81 ->setColorspace($this->getToolkit()->getExecManager()->getPackage() === 'imagemagick' ? 'sRGB' : NULL)
84 $this->getToolkit()->arguments()
85 ->setSourceFormatFromExtension($arguments['extension'])
86 ->setSourceLocalPath('')
88 $arg = '-size ' . $arguments['width'] . 'x' . $arguments['height'];
90 // Transparent color syntax for GIF files differs by package.
91 if ($arguments['extension'] === 'gif') {
92 switch ($this->getToolkit()->getExecManager()->getPackage()) {
94 $arg .= ' xc:transparent -transparent-color ' . $this->escapeArgument($arguments['transparent_color']);
97 case 'graphicsmagick':
98 $arg .= ' xc:' . $this->escapeArgument($arguments['transparent_color']) . ' -transparent ' . $this->escapeArgument($arguments['transparent_color']);
104 $arg .= ' xc:transparent';
107 $this->addArgument($arg);