ILIAS  trunk Revision v11.0_alpha-2645-g16283d3b3f8
ImageOutputOptions.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
22 
27 {
28  public const FORMAT_JPG = 'jpg';
29  public const FORMAT_PNG = 'png';
30  public const FORMAT_WEBP = 'webp';
31  public const FORMAT_KEEP = 'keep';
32  private int $quality = 75;
33  private string $format = self::FORMAT_JPG;
34  private array $allowed_formats = [
35  self::FORMAT_JPG,
36  self::FORMAT_PNG,
37  self::FORMAT_WEBP,
38  self::FORMAT_KEEP,
39  ];
40 
45  public function withFormat(string $format): ImageOutputOptions
46  {
47  $format = $this->checkFormat($format);
48  $clone = clone $this;
49  $clone->format = $format;
50  return $clone;
51  }
52 
56  public function withJpgOutput(): ImageOutputOptions
57  {
58  return $this->withFormat(self::FORMAT_JPG);
59  }
60 
64  public function withPngOutput(): ImageOutputOptions
65  {
66  return $this->withFormat(self::FORMAT_PNG);
67  }
68 
73  {
74  return $this->withFormat(self::FORMAT_WEBP);
75  }
76 
83  public function withQuality(int $image_quality): ImageOutputOptions
84  {
85  $this->checkImageQuality($image_quality);
86  $clone = clone $this;
87  $clone->quality = $image_quality;
88  return $clone;
89  }
90 
91  public function getFormat(): string
92  {
93  return $this->format;
94  }
95 
96  public function getQuality(): int
97  {
98  return $this->quality;
99  }
100 
101  private function checkFormat(string $format): string
102  {
103  $format = strtolower($format);
104  if ($format === 'jpeg') {
105  $format = self::FORMAT_JPG;
106  }
107 
108  if (!in_array($format, $this->allowed_formats, true)) {
109  throw new \InvalidArgumentException('Format must be one of ' . implode(', ',$this->allowed_formats) . ', but ' . $format . ' was given.');
110  }
111  return $format;
112  }
113 
114  protected function checkImageQuality(int $image_quality): void
115  {
116  if ($this->format === self::FORMAT_WEBP) {
117  if ($image_quality !== 0 && $image_quality !== 100) {
118  throw new \InvalidArgumentException('WebP only supports quality 0 (loss) or 100 (losless)');
119  }
120  } elseif ($image_quality < 0 || $image_quality > 100) {
121  throw new \InvalidArgumentException('Quality must be between 0 and 100');
122  }
123  }
124 }
withQuality(int $image_quality)
set the image compression quality.
withFormat(string $format)
set the desired output format.