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) {
79 ->setSourceLocalPath('')
80 ->setSourceFormatFromExtension($arguments['extension'])
81 ->setWidth($arguments['width'])
82 ->setHeight($arguments['height'])
83 ->setExifOrientation(NULL)
85 $arg = '-size ' . $arguments['width'] . 'x' . $arguments['height'];
87 // Transparent color syntax for GIF files differs by package.
88 if ($arguments['extension'] === 'gif') {
89 switch ($this->getToolkit()->getPackage()) {
91 $arg .= ' xc:transparent -transparent-color ' . $this->getToolkit()->escapeShellArg($arguments['transparent_color']);
94 case 'graphicsmagick':
95 $arg .= ' xc:' . $this->getToolkit()->escapeShellArg($arguments['transparent_color']) . ' -transparent ' . $this->getToolkit()->escapeShellArg($arguments['transparent_color']);
101 $arg .= ' xc:transparent';
104 $this->getToolkit()->addArgument($arg);