3 namespace Drupal\system\Plugin\ImageToolkit\Operation\gd;
6 * Defines GD2 Scale operation.
8 * @ImageToolkitOperation(
11 * operation = "scale",
12 * label = @Translation("Scale"),
13 * description = @Translation("Scales an image while maintaining aspect ratio. The resulting image can be smaller for one or both target dimensions.")
16 class Scale extends Resize {
21 protected function arguments() {
24 'description' => 'The target width, in pixels. This value is omitted then the scaling will based only on the height value',
29 'description' => 'The target height, in pixels. This value is omitted then the scaling will based only on the width value',
34 'description' => 'Boolean indicating that files smaller than the dimensions will be scaled up. This generally results in a low quality image',
44 protected function validateArguments(array $arguments) {
45 // Assure at least one dimension.
46 if (empty($arguments['width']) && empty($arguments['height'])) {
47 throw new \InvalidArgumentException("At least one dimension ('width' or 'height') must be provided to the image 'scale' operation");
50 // Calculate one of the dimensions from the other target dimension,
51 // ensuring the same aspect ratio as the source dimensions. If one of the
52 // target dimensions is missing, that is the one that is calculated. If both
53 // are specified then the dimension calculated is the one that would not be
54 // calculated to be bigger than its target.
55 $aspect = $this->getToolkit()->getHeight() / $this->getToolkit()->getWidth();
56 if (($arguments['width'] && !$arguments['height']) || ($arguments['width'] && $arguments['height'] && $aspect < $arguments['height'] / $arguments['width'])) {
57 $arguments['height'] = (int) round($arguments['width'] * $aspect);
60 $arguments['width'] = (int) round($arguments['height'] / $aspect);
63 // Assure integers for all arguments.
64 $arguments['width'] = (int) round($arguments['width']);
65 $arguments['height'] = (int) round($arguments['height']);
67 // Fail when width or height are 0 or negative.
68 if ($arguments['width'] <= 0) {
69 throw new \InvalidArgumentException("Invalid width ('{$arguments['width']}') specified for the image 'scale' operation");
71 if ($arguments['height'] <= 0) {
72 throw new \InvalidArgumentException("Invalid height ('{$arguments['height']}') specified for the image 'scale' operation");
81 protected function execute(array $arguments = []) {
82 // Don't scale if we don't change the dimensions at all.
83 if ($arguments['width'] !== $this->getToolkit()->getWidth() || $arguments['height'] !== $this->getToolkit()->getHeight()) {
84 // Don't upscale if the option isn't enabled.
85 if ($arguments['upscale'] || ($arguments['width'] <= $this->getToolkit()->getWidth() && $arguments['height'] <= $this->getToolkit()->getHeight())) {
86 return parent::execute($arguments);