Version 1
[yaffs-website] / web / core / modules / system / src / Plugin / ImageToolkit / Operation / gd / Convert.php
1 <?php
2
3 namespace Drupal\system\Plugin\ImageToolkit\Operation\gd;
4
5 /**
6  * Defines GD2 convert operation.
7  *
8  * @ImageToolkitOperation(
9  *   id = "gd_convert",
10  *   toolkit = "gd",
11  *   operation = "convert",
12  *   label = @Translation("Convert"),
13  *   description = @Translation("Instructs the toolkit to save the image with a specified extension.")
14  * )
15  */
16 class Convert extends GDImageToolkitOperationBase {
17
18   /**
19    * {@inheritdoc}
20    */
21   protected function arguments() {
22     return [
23       'extension' => [
24         'description' => 'The new extension of the converted image',
25       ],
26     ];
27   }
28
29   /**
30    * {@inheritdoc}
31    */
32   protected function validateArguments(array $arguments) {
33     if (!in_array($arguments['extension'], $this->getToolkit()->getSupportedExtensions())) {
34       throw new \InvalidArgumentException("Invalid extension ({$arguments['extension']}) specified for the image 'convert' operation");
35     }
36     return $arguments;
37   }
38
39   /**
40    * {@inheritdoc}
41    */
42   protected function execute(array $arguments) {
43     // Create a new resource of the required dimensions and format, and copy
44     // the original resource on it with resampling. Destroy the original
45     // resource upon success.
46     $width = $this->getToolkit()->getWidth();
47     $height = $this->getToolkit()->getHeight();
48     $original_resource = $this->getToolkit()->getResource();
49     $original_type = $this->getToolkit()->getType();
50     $data = [
51       'width' => $width,
52       'height' => $height,
53       'extension' => $arguments['extension'],
54       'transparent_color' => $this->getToolkit()->getTransparentColor(),
55       'is_temp' => TRUE,
56     ];
57     if ($this->getToolkit()->apply('create_new', $data)) {
58       if (imagecopyresampled($this->getToolkit()->getResource(), $original_resource, 0, 0, 0, 0, $width, $height, $width, $height)) {
59         imagedestroy($original_resource);
60         return TRUE;
61       }
62       // In case of error, reset resource and type to as it was.
63       $this->getToolkit()->setResource($original_resource);
64       $this->getToolkit()->setType($original_type);
65     }
66     return FALSE;
67   }
68
69 }