Version 1
[yaffs-website] / web / modules / contrib / imagemagick / src / Plugin / ImageToolkit / Operation / imagemagick / ScaleAndCrop.php
1 <?php
2
3 namespace Drupal\imagemagick\Plugin\ImageToolkit\Operation\imagemagick;
4
5 /**
6  * Defines imagemagick Scale and crop operation.
7  *
8  * @ImageToolkitOperation(
9  *   id = "imagemagick_scale_and_crop",
10  *   toolkit = "imagemagick",
11  *   operation = "scale_and_crop",
12  *   label = @Translation("Scale and crop"),
13  *   description = @Translation("Scales an image to the exact width and height given. This plugin achieves the target aspect ratio by cropping the original image equally on both sides, or equally on the top and bottom. This function is useful to create uniform sized avatars from larger images.")
14  * )
15  */
16 class ScaleAndCrop extends ImagemagickImageToolkitOperationBase {
17
18   /**
19    * {@inheritdoc}
20    */
21   protected function arguments() {
22     return [
23       'width' => [
24         'description' => 'The target width, in pixels',
25       ],
26       'height' => [
27         'description' => 'The target height, in pixels',
28       ],
29       'filter' => [
30         'description' => 'An optional filter to apply for the resize',
31         'required' => FALSE,
32         'default' => '',
33       ],
34     ];
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   protected function validateArguments(array $arguments) {
41     $actual_width = $this->getToolkit()->getWidth();
42     $actual_height = $this->getToolkit()->getHeight();
43
44     $scale_factor = max($arguments['width'] / $actual_width, $arguments['height'] / $actual_height);
45
46     $arguments['x'] = (int) round(($actual_width * $scale_factor - $arguments['width']) / 2);
47     $arguments['y'] = (int) round(($actual_height * $scale_factor - $arguments['height']) / 2);
48     $arguments['resize'] = [
49       'width' => (int) round($actual_width * $scale_factor),
50       'height' => (int) round($actual_height * $scale_factor),
51       'filter' => $arguments['filter'],
52     ];
53
54     // Fail when width or height are 0 or negative.
55     if ($arguments['width'] <= 0) {
56       throw new \InvalidArgumentException("Invalid width ('{$arguments['width']}') specified for the image 'scale_and_crop' operation");
57     }
58     if ($arguments['height'] <= 0) {
59       throw new \InvalidArgumentException("Invalid height ('{$arguments['height']}') specified for the image 'scale_and_crop' operation");
60     }
61
62     return $arguments;
63   }
64
65   /**
66    * {@inheritdoc}
67    */
68   protected function execute(array $arguments = []) {
69     return $this->getToolkit()->apply('resize', $arguments['resize'])
70         && $this->getToolkit()->apply('crop', $arguments);
71   }
72
73 }