@vituum/vite-plugin-latte 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/package.json +6 -6
  2. package/vendor/autoload.php +1 -1
  3. package/vendor/composer/autoload_classmap.php +49 -0
  4. package/vendor/composer/autoload_real.php +4 -4
  5. package/vendor/composer/autoload_static.php +51 -2
  6. package/vendor/composer/installed.json +102 -12
  7. package/vendor/composer/installed.php +14 -5
  8. package/vendor/latte/latte/composer.json +6 -5
  9. package/vendor/latte/latte/readme.md +27 -9
  10. package/vendor/latte/latte/src/Bridges/Tracy/templates/LattePanel.panel.phtml +4 -1
  11. package/vendor/latte/latte/src/Latte/Compiler/TagLexer.php +1 -1
  12. package/vendor/latte/latte/src/Latte/Compiler/TagParserData.php +129 -129
  13. package/vendor/latte/latte/src/Latte/Compiler/TemplateGenerator.php +1 -1
  14. package/vendor/latte/latte/src/Latte/Compiler/TemplateParser.php +1 -1
  15. package/vendor/latte/latte/src/Latte/Engine.php +22 -2
  16. package/vendor/latte/latte/src/Latte/Essential/CachingIterator.php +2 -3
  17. package/vendor/latte/latte/src/Latte/Essential/CoreExtension.php +9 -1
  18. package/vendor/latte/latte/src/Latte/Essential/Filters.php +110 -10
  19. package/vendor/latte/latte/src/Latte/Essential/Nodes/ImportNode.php +8 -2
  20. package/vendor/latte/latte/src/Latte/Essential/Nodes/VarNode.php +14 -18
  21. package/vendor/latte/latte/src/Latte/Essential/TranslatorExtension.php +1 -1
  22. package/vendor/latte/latte/src/Latte/Loaders/FileLoader.php +5 -4
  23. package/vendor/latte/latte/src/Latte/Runtime/Template.php +1 -1
  24. package/vendor/latte/latte/src/Latte/Sandbox/Nodes/FunctionCallNode.php +0 -1
  25. package/vendor/nette/utils/.phpstorm.meta.php +13 -0
  26. package/vendor/nette/utils/composer.json +51 -0
  27. package/vendor/nette/utils/license.md +60 -0
  28. package/vendor/nette/utils/readme.md +55 -0
  29. package/vendor/nette/utils/src/HtmlStringable.php +22 -0
  30. package/vendor/nette/utils/src/Iterators/CachingIterator.php +150 -0
  31. package/vendor/nette/utils/src/Iterators/Mapper.php +33 -0
  32. package/vendor/nette/utils/src/SmartObject.php +140 -0
  33. package/vendor/nette/utils/src/StaticClass.php +34 -0
  34. package/vendor/nette/utils/src/Translator.php +25 -0
  35. package/vendor/nette/utils/src/Utils/ArrayHash.php +106 -0
  36. package/vendor/nette/utils/src/Utils/ArrayList.php +136 -0
  37. package/vendor/nette/utils/src/Utils/Arrays.php +553 -0
  38. package/vendor/nette/utils/src/Utils/Callback.php +137 -0
  39. package/vendor/nette/utils/src/Utils/DateTime.php +140 -0
  40. package/vendor/nette/utils/src/Utils/FileInfo.php +69 -0
  41. package/vendor/nette/utils/src/Utils/FileSystem.php +326 -0
  42. package/vendor/nette/utils/src/Utils/Finder.php +510 -0
  43. package/vendor/nette/utils/src/Utils/Floats.php +107 -0
  44. package/vendor/nette/utils/src/Utils/Helpers.php +104 -0
  45. package/vendor/nette/utils/src/Utils/Html.php +839 -0
  46. package/vendor/nette/utils/src/Utils/Image.php +831 -0
  47. package/vendor/nette/utils/src/Utils/ImageColor.php +75 -0
  48. package/vendor/nette/utils/src/Utils/ImageType.php +25 -0
  49. package/vendor/nette/utils/src/Utils/Iterables.php +238 -0
  50. package/vendor/nette/utils/src/Utils/Json.php +84 -0
  51. package/vendor/nette/utils/src/Utils/ObjectHelpers.php +229 -0
  52. package/vendor/nette/utils/src/Utils/Paginator.php +245 -0
  53. package/vendor/nette/utils/src/Utils/Random.php +52 -0
  54. package/vendor/nette/utils/src/Utils/Reflection.php +322 -0
  55. package/vendor/nette/utils/src/Utils/ReflectionMethod.php +36 -0
  56. package/vendor/nette/utils/src/Utils/Strings.php +728 -0
  57. package/vendor/nette/utils/src/Utils/Type.php +267 -0
  58. package/vendor/nette/utils/src/Utils/Validators.php +416 -0
  59. package/vendor/nette/utils/src/Utils/exceptions.php +50 -0
  60. package/vendor/nette/utils/src/compatibility.php +32 -0
  61. package/vendor/nette/utils/src/exceptions.php +109 -0
@@ -0,0 +1,831 @@
1
+ <?php
2
+
3
+ /**
4
+ * This file is part of the Nette Framework (https://nette.org)
5
+ * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
+ */
7
+
8
+ declare(strict_types=1);
9
+
10
+ namespace Nette\Utils;
11
+
12
+ use Nette;
13
+
14
+
15
+ /**
16
+ * Basic manipulation with images. Supported types are JPEG, PNG, GIF, WEBP, AVIF and BMP.
17
+ *
18
+ * <code>
19
+ * $image = Image::fromFile('nette.jpg');
20
+ * $image->resize(150, 100);
21
+ * $image->sharpen();
22
+ * $image->send();
23
+ * </code>
24
+ *
25
+ * @method Image affine(array $affine, ?array $clip = null)
26
+ * @method void alphaBlending(bool $enable)
27
+ * @method void antialias(bool $enable)
28
+ * @method void arc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color)
29
+ * @method int colorAllocate(int $red, int $green, int $blue)
30
+ * @method int colorAllocateAlpha(int $red, int $green, int $blue, int $alpha)
31
+ * @method int colorAt(int $x, int $y)
32
+ * @method int colorClosest(int $red, int $green, int $blue)
33
+ * @method int colorClosestAlpha(int $red, int $green, int $blue, int $alpha)
34
+ * @method int colorClosestHWB(int $red, int $green, int $blue)
35
+ * @method void colorDeallocate(int $color)
36
+ * @method int colorExact(int $red, int $green, int $blue)
37
+ * @method int colorExactAlpha(int $red, int $green, int $blue, int $alpha)
38
+ * @method void colorMatch(Image $image2)
39
+ * @method int colorResolve(int $red, int $green, int $blue)
40
+ * @method int colorResolveAlpha(int $red, int $green, int $blue, int $alpha)
41
+ * @method void colorSet(int $index, int $red, int $green, int $blue, int $alpha = 0)
42
+ * @method array colorsForIndex(int $color)
43
+ * @method int colorsTotal()
44
+ * @method int colorTransparent(?int $color = null)
45
+ * @method void convolution(array $matrix, float $div, float $offset)
46
+ * @method void copy(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH)
47
+ * @method void copyMerge(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)
48
+ * @method void copyMergeGray(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)
49
+ * @method void copyResampled(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)
50
+ * @method void copyResized(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)
51
+ * @method Image cropAuto(int $mode = IMG_CROP_DEFAULT, float $threshold = .5, ?ImageColor $color = null)
52
+ * @method void ellipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color)
53
+ * @method void fill(int $x, int $y, ImageColor $color)
54
+ * @method void filledArc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color, int $style)
55
+ * @method void filledEllipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color)
56
+ * @method void filledPolygon(array $points, ImageColor $color)
57
+ * @method void filledRectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
58
+ * @method void fillToBorder(int $x, int $y, ImageColor $borderColor, ImageColor $color)
59
+ * @method void filter(int $filter, ...$args)
60
+ * @method void flip(int $mode)
61
+ * @method array ftText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options = [])
62
+ * @method void gammaCorrect(float $inputgamma, float $outputgamma)
63
+ * @method array getClip()
64
+ * @method int getInterpolation()
65
+ * @method int interlace(?bool $enable = null)
66
+ * @method bool isTrueColor()
67
+ * @method void layerEffect(int $effect)
68
+ * @method void line(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
69
+ * @method void openPolygon(array $points, ImageColor $color)
70
+ * @method void paletteCopy(Image $source)
71
+ * @method void paletteToTrueColor()
72
+ * @method void polygon(array $points, ImageColor $color)
73
+ * @method void rectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
74
+ * @method mixed resolution(?int $resolutionX = null, ?int $resolutionY = null)
75
+ * @method Image rotate(float $angle, ImageColor $backgroundColor)
76
+ * @method void saveAlpha(bool $enable)
77
+ * @method Image scale(int $newWidth, int $newHeight = -1, int $mode = IMG_BILINEAR_FIXED)
78
+ * @method void setBrush(Image $brush)
79
+ * @method void setClip(int $x1, int $y1, int $x2, int $y2)
80
+ * @method void setInterpolation(int $method = IMG_BILINEAR_FIXED)
81
+ * @method void setPixel(int $x, int $y, ImageColor $color)
82
+ * @method void setStyle(array $style)
83
+ * @method void setThickness(int $thickness)
84
+ * @method void setTile(Image $tile)
85
+ * @method void trueColorToPalette(bool $dither, int $ncolors)
86
+ * @method array ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontfile, string $text, array $options = [])
87
+ * @property-read positive-int $width
88
+ * @property-read positive-int $height
89
+ * @property-read \GdImage $imageResource
90
+ */
91
+ class Image
92
+ {
93
+ use Nette\SmartObject;
94
+
95
+ /** Prevent from getting resized to a bigger size than the original */
96
+ public const ShrinkOnly = 0b0001;
97
+
98
+ /** Resizes to a specified width and height without keeping aspect ratio */
99
+ public const Stretch = 0b0010;
100
+
101
+ /** Resizes to fit into a specified width and height and preserves aspect ratio */
102
+ public const OrSmaller = 0b0000;
103
+
104
+ /** Resizes while bounding the smaller dimension to the specified width or height and preserves aspect ratio */
105
+ public const OrBigger = 0b0100;
106
+
107
+ /** Resizes to the smallest possible size to completely cover specified width and height and reserves aspect ratio */
108
+ public const Cover = 0b1000;
109
+
110
+ /** @deprecated use Image::ShrinkOnly */
111
+ public const SHRINK_ONLY = self::ShrinkOnly;
112
+
113
+ /** @deprecated use Image::Stretch */
114
+ public const STRETCH = self::Stretch;
115
+
116
+ /** @deprecated use Image::OrSmaller */
117
+ public const FIT = self::OrSmaller;
118
+
119
+ /** @deprecated use Image::OrBigger */
120
+ public const FILL = self::OrBigger;
121
+
122
+ /** @deprecated use Image::Cover */
123
+ public const EXACT = self::Cover;
124
+
125
+ /** @deprecated use Image::EmptyGIF */
126
+ public const EMPTY_GIF = self::EmptyGIF;
127
+
128
+ /** image types */
129
+ public const
130
+ JPEG = ImageType::JPEG,
131
+ PNG = ImageType::PNG,
132
+ GIF = ImageType::GIF,
133
+ WEBP = ImageType::WEBP,
134
+ AVIF = ImageType::AVIF,
135
+ BMP = ImageType::BMP;
136
+
137
+ public const EmptyGIF = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
138
+
139
+ private const Formats = [ImageType::JPEG => 'jpeg', ImageType::PNG => 'png', ImageType::GIF => 'gif', ImageType::WEBP => 'webp', ImageType::AVIF => 'avif', ImageType::BMP => 'bmp'];
140
+
141
+ private \GdImage $image;
142
+
143
+
144
+ /**
145
+ * Returns RGB color (0..255) and transparency (0..127).
146
+ * @deprecated use ImageColor::rgb()
147
+ */
148
+ public static function rgb(int $red, int $green, int $blue, int $transparency = 0): array
149
+ {
150
+ return [
151
+ 'red' => max(0, min(255, $red)),
152
+ 'green' => max(0, min(255, $green)),
153
+ 'blue' => max(0, min(255, $blue)),
154
+ 'alpha' => max(0, min(127, $transparency)),
155
+ ];
156
+ }
157
+
158
+
159
+ /**
160
+ * Reads an image from a file and returns its type in $type.
161
+ * @throws Nette\NotSupportedException if gd extension is not loaded
162
+ * @throws UnknownImageFileException if file not found or file type is not known
163
+ */
164
+ public static function fromFile(string $file, ?int &$type = null): static
165
+ {
166
+ self::ensureExtension();
167
+ $type = self::detectTypeFromFile($file);
168
+ if (!$type) {
169
+ throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
170
+ }
171
+
172
+ return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__);
173
+ }
174
+
175
+
176
+ /**
177
+ * Reads an image from a string and returns its type in $type.
178
+ * @throws Nette\NotSupportedException if gd extension is not loaded
179
+ * @throws ImageException
180
+ */
181
+ public static function fromString(string $s, ?int &$type = null): static
182
+ {
183
+ self::ensureExtension();
184
+ $type = self::detectTypeFromString($s);
185
+ if (!$type) {
186
+ throw new UnknownImageFileException('Unknown type of image.');
187
+ }
188
+
189
+ return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__);
190
+ }
191
+
192
+
193
+ private static function invokeSafe(string $func, string $arg, string $message, string $callee): static
194
+ {
195
+ $errors = [];
196
+ $res = Callback::invokeSafe($func, [$arg], function (string $message) use (&$errors): void {
197
+ $errors[] = $message;
198
+ });
199
+
200
+ if (!$res) {
201
+ throw new ImageException($message . ' Errors: ' . implode(', ', $errors));
202
+ } elseif ($errors) {
203
+ trigger_error($callee . '(): ' . implode(', ', $errors), E_USER_WARNING);
204
+ }
205
+
206
+ return new static($res);
207
+ }
208
+
209
+
210
+ /**
211
+ * Creates a new true color image of the given dimensions. The default color is black.
212
+ * @param positive-int $width
213
+ * @param positive-int $height
214
+ * @throws Nette\NotSupportedException if gd extension is not loaded
215
+ */
216
+ public static function fromBlank(int $width, int $height, ImageColor|array|null $color = null): static
217
+ {
218
+ self::ensureExtension();
219
+ if ($width < 1 || $height < 1) {
220
+ throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.');
221
+ }
222
+
223
+ $image = new static(imagecreatetruecolor($width, $height));
224
+ if ($color) {
225
+ $image->alphablending(false);
226
+ $image->filledrectangle(0, 0, $width - 1, $height - 1, $color);
227
+ $image->alphablending(true);
228
+ }
229
+
230
+ return $image;
231
+ }
232
+
233
+
234
+ /**
235
+ * Returns the type of image from file.
236
+ * @return ImageType::*|null
237
+ */
238
+ public static function detectTypeFromFile(string $file, &$width = null, &$height = null): ?int
239
+ {
240
+ [$width, $height, $type] = @getimagesize($file); // @ - files smaller than 12 bytes causes read error
241
+ return isset(self::Formats[$type]) ? $type : null;
242
+ }
243
+
244
+
245
+ /**
246
+ * Returns the type of image from string.
247
+ * @return ImageType::*|null
248
+ */
249
+ public static function detectTypeFromString(string $s, &$width = null, &$height = null): ?int
250
+ {
251
+ [$width, $height, $type] = @getimagesizefromstring($s); // @ - strings smaller than 12 bytes causes read error
252
+ return isset(self::Formats[$type]) ? $type : null;
253
+ }
254
+
255
+
256
+ /**
257
+ * Returns the file extension for the given image type.
258
+ * @param ImageType::* $type
259
+ * @return value-of<self::Formats>
260
+ */
261
+ public static function typeToExtension(int $type): string
262
+ {
263
+ if (!isset(self::Formats[$type])) {
264
+ throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
265
+ }
266
+
267
+ return self::Formats[$type];
268
+ }
269
+
270
+
271
+ /**
272
+ * Returns the image type for given file extension.
273
+ * @return ImageType::*
274
+ */
275
+ public static function extensionToType(string $extension): int
276
+ {
277
+ $extensions = array_flip(self::Formats) + ['jpg' => ImageType::JPEG];
278
+ $extension = strtolower($extension);
279
+ if (!isset($extensions[$extension])) {
280
+ throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'.");
281
+ }
282
+
283
+ return $extensions[$extension];
284
+ }
285
+
286
+
287
+ /**
288
+ * Returns the mime type for the given image type.
289
+ * @param ImageType::* $type
290
+ */
291
+ public static function typeToMimeType(int $type): string
292
+ {
293
+ return 'image/' . self::typeToExtension($type);
294
+ }
295
+
296
+
297
+ /**
298
+ * @param ImageType::* $type
299
+ */
300
+ public static function isTypeSupported(int $type): bool
301
+ {
302
+ self::ensureExtension();
303
+ return (bool) (imagetypes() & match ($type) {
304
+ ImageType::JPEG => IMG_JPG,
305
+ ImageType::PNG => IMG_PNG,
306
+ ImageType::GIF => IMG_GIF,
307
+ ImageType::WEBP => IMG_WEBP,
308
+ ImageType::AVIF => 256, // IMG_AVIF,
309
+ ImageType::BMP => IMG_BMP,
310
+ default => 0,
311
+ });
312
+ }
313
+
314
+
315
+ /** @return ImageType[] */
316
+ public static function getSupportedTypes(): array
317
+ {
318
+ self::ensureExtension();
319
+ $flag = imagetypes();
320
+ return array_filter([
321
+ $flag & IMG_GIF ? ImageType::GIF : null,
322
+ $flag & IMG_JPG ? ImageType::JPEG : null,
323
+ $flag & IMG_PNG ? ImageType::PNG : null,
324
+ $flag & IMG_WEBP ? ImageType::WEBP : null,
325
+ $flag & 256 ? ImageType::AVIF : null, // IMG_AVIF
326
+ $flag & IMG_BMP ? ImageType::BMP : null,
327
+ ]);
328
+ }
329
+
330
+
331
+ /**
332
+ * Wraps GD image.
333
+ */
334
+ public function __construct(\GdImage $image)
335
+ {
336
+ $this->setImageResource($image);
337
+ imagesavealpha($image, true);
338
+ }
339
+
340
+
341
+ /**
342
+ * Returns image width.
343
+ * @return positive-int
344
+ */
345
+ public function getWidth(): int
346
+ {
347
+ return imagesx($this->image);
348
+ }
349
+
350
+
351
+ /**
352
+ * Returns image height.
353
+ * @return positive-int
354
+ */
355
+ public function getHeight(): int
356
+ {
357
+ return imagesy($this->image);
358
+ }
359
+
360
+
361
+ /**
362
+ * Sets image resource.
363
+ */
364
+ protected function setImageResource(\GdImage $image): static
365
+ {
366
+ $this->image = $image;
367
+ return $this;
368
+ }
369
+
370
+
371
+ /**
372
+ * Returns image GD resource.
373
+ */
374
+ public function getImageResource(): \GdImage
375
+ {
376
+ return $this->image;
377
+ }
378
+
379
+
380
+ /**
381
+ * Scales an image. Width and height accept pixels or percent.
382
+ * @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode
383
+ */
384
+ public function resize(int|string|null $width, int|string|null $height, int $mode = self::OrSmaller): static
385
+ {
386
+ if ($mode & self::Cover) {
387
+ return $this->resize($width, $height, self::OrBigger)->crop('50%', '50%', $width, $height);
388
+ }
389
+
390
+ [$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $mode);
391
+
392
+ if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize
393
+ $newImage = static::fromBlank($newWidth, $newHeight, ImageColor::rgb(0, 0, 0, 0))->getImageResource();
394
+ imagecopyresampled(
395
+ $newImage,
396
+ $this->image,
397
+ 0,
398
+ 0,
399
+ 0,
400
+ 0,
401
+ $newWidth,
402
+ $newHeight,
403
+ $this->getWidth(),
404
+ $this->getHeight(),
405
+ );
406
+ $this->image = $newImage;
407
+ }
408
+
409
+ if ($width < 0 || $height < 0) {
410
+ imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL);
411
+ }
412
+
413
+ return $this;
414
+ }
415
+
416
+
417
+ /**
418
+ * Calculates dimensions of resized image. Width and height accept pixels or percent.
419
+ * @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode
420
+ */
421
+ public static function calculateSize(
422
+ int $srcWidth,
423
+ int $srcHeight,
424
+ $newWidth,
425
+ $newHeight,
426
+ int $mode = self::OrSmaller,
427
+ ): array
428
+ {
429
+ if ($newWidth === null) {
430
+ } elseif (self::isPercent($newWidth)) {
431
+ $newWidth = (int) round($srcWidth / 100 * abs($newWidth));
432
+ $percents = true;
433
+ } else {
434
+ $newWidth = abs($newWidth);
435
+ }
436
+
437
+ if ($newHeight === null) {
438
+ } elseif (self::isPercent($newHeight)) {
439
+ $newHeight = (int) round($srcHeight / 100 * abs($newHeight));
440
+ $mode |= empty($percents) ? 0 : self::Stretch;
441
+ } else {
442
+ $newHeight = abs($newHeight);
443
+ }
444
+
445
+ if ($mode & self::Stretch) { // non-proportional
446
+ if (!$newWidth || !$newHeight) {
447
+ throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.');
448
+ }
449
+
450
+ if ($mode & self::ShrinkOnly) {
451
+ $newWidth = min($srcWidth, $newWidth);
452
+ $newHeight = min($srcHeight, $newHeight);
453
+ }
454
+ } else { // proportional
455
+ if (!$newWidth && !$newHeight) {
456
+ throw new Nette\InvalidArgumentException('At least width or height must be specified.');
457
+ }
458
+
459
+ $scale = [];
460
+ if ($newWidth > 0) { // fit width
461
+ $scale[] = $newWidth / $srcWidth;
462
+ }
463
+
464
+ if ($newHeight > 0) { // fit height
465
+ $scale[] = $newHeight / $srcHeight;
466
+ }
467
+
468
+ if ($mode & self::OrBigger) {
469
+ $scale = [max($scale)];
470
+ }
471
+
472
+ if ($mode & self::ShrinkOnly) {
473
+ $scale[] = 1;
474
+ }
475
+
476
+ $scale = min($scale);
477
+ $newWidth = (int) round($srcWidth * $scale);
478
+ $newHeight = (int) round($srcHeight * $scale);
479
+ }
480
+
481
+ return [max($newWidth, 1), max($newHeight, 1)];
482
+ }
483
+
484
+
485
+ /**
486
+ * Crops image. Arguments accepts pixels or percent.
487
+ */
488
+ public function crop(int|string $left, int|string $top, int|string $width, int|string $height): static
489
+ {
490
+ [$r['x'], $r['y'], $r['width'], $r['height']]
491
+ = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
492
+ if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') {
493
+ $this->image = imagecrop($this->image, $r);
494
+ imagesavealpha($this->image, true);
495
+ } else {
496
+ $newImage = static::fromBlank($r['width'], $r['height'], ImageColor::rgb(0, 0, 0, 0))->getImageResource();
497
+ imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']);
498
+ $this->image = $newImage;
499
+ }
500
+
501
+ return $this;
502
+ }
503
+
504
+
505
+ /**
506
+ * Calculates dimensions of cutout in image. Arguments accepts pixels or percent.
507
+ */
508
+ public static function calculateCutout(
509
+ int $srcWidth,
510
+ int $srcHeight,
511
+ int|string $left,
512
+ int|string $top,
513
+ int|string $newWidth,
514
+ int|string $newHeight,
515
+ ): array
516
+ {
517
+ if (self::isPercent($newWidth)) {
518
+ $newWidth = (int) round($srcWidth / 100 * $newWidth);
519
+ }
520
+
521
+ if (self::isPercent($newHeight)) {
522
+ $newHeight = (int) round($srcHeight / 100 * $newHeight);
523
+ }
524
+
525
+ if (self::isPercent($left)) {
526
+ $left = (int) round(($srcWidth - $newWidth) / 100 * $left);
527
+ }
528
+
529
+ if (self::isPercent($top)) {
530
+ $top = (int) round(($srcHeight - $newHeight) / 100 * $top);
531
+ }
532
+
533
+ if ($left < 0) {
534
+ $newWidth += $left;
535
+ $left = 0;
536
+ }
537
+
538
+ if ($top < 0) {
539
+ $newHeight += $top;
540
+ $top = 0;
541
+ }
542
+
543
+ $newWidth = min($newWidth, $srcWidth - $left);
544
+ $newHeight = min($newHeight, $srcHeight - $top);
545
+ return [$left, $top, $newWidth, $newHeight];
546
+ }
547
+
548
+
549
+ /**
550
+ * Sharpens image a little bit.
551
+ */
552
+ public function sharpen(): static
553
+ {
554
+ imageconvolution($this->image, [ // my magic numbers ;)
555
+ [-1, -1, -1],
556
+ [-1, 24, -1],
557
+ [-1, -1, -1],
558
+ ], 16, 0);
559
+ return $this;
560
+ }
561
+
562
+
563
+ /**
564
+ * Puts another image into this image. Left and top accepts pixels or percent.
565
+ * @param int<0, 100> $opacity 0..100
566
+ */
567
+ public function place(self $image, int|string $left = 0, int|string $top = 0, int $opacity = 100): static
568
+ {
569
+ $opacity = max(0, min(100, $opacity));
570
+ if ($opacity === 0) {
571
+ return $this;
572
+ }
573
+
574
+ $width = $image->getWidth();
575
+ $height = $image->getHeight();
576
+
577
+ if (self::isPercent($left)) {
578
+ $left = (int) round(($this->getWidth() - $width) / 100 * $left);
579
+ }
580
+
581
+ if (self::isPercent($top)) {
582
+ $top = (int) round(($this->getHeight() - $height) / 100 * $top);
583
+ }
584
+
585
+ $output = $input = $image->image;
586
+ if ($opacity < 100) {
587
+ $tbl = [];
588
+ for ($i = 0; $i < 128; $i++) {
589
+ $tbl[$i] = round(127 - (127 - $i) * $opacity / 100);
590
+ }
591
+
592
+ $output = imagecreatetruecolor($width, $height);
593
+ imagealphablending($output, false);
594
+ if (!$image->isTrueColor()) {
595
+ $input = $output;
596
+ imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127));
597
+ imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height);
598
+ }
599
+
600
+ for ($x = 0; $x < $width; $x++) {
601
+ for ($y = 0; $y < $height; $y++) {
602
+ $c = \imagecolorat($input, $x, $y);
603
+ $c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24);
604
+ \imagesetpixel($output, $x, $y, $c);
605
+ }
606
+ }
607
+
608
+ imagealphablending($output, true);
609
+ }
610
+
611
+ imagecopy(
612
+ $this->image,
613
+ $output,
614
+ $left,
615
+ $top,
616
+ 0,
617
+ 0,
618
+ $width,
619
+ $height,
620
+ );
621
+ return $this;
622
+ }
623
+
624
+
625
+ /**
626
+ * Calculates the bounding box for a TrueType text. Returns keys left, top, width and height.
627
+ */
628
+ public static function calculateTextBox(
629
+ string $text,
630
+ string $fontFile,
631
+ float $size,
632
+ float $angle = 0,
633
+ array $options = [],
634
+ ): array
635
+ {
636
+ self::ensureExtension();
637
+ $box = imagettfbbox($size, $angle, $fontFile, $text, $options);
638
+ return [
639
+ 'left' => $minX = min([$box[0], $box[2], $box[4], $box[6]]),
640
+ 'top' => $minY = min([$box[1], $box[3], $box[5], $box[7]]),
641
+ 'width' => max([$box[0], $box[2], $box[4], $box[6]]) - $minX + 1,
642
+ 'height' => max([$box[1], $box[3], $box[5], $box[7]]) - $minY + 1,
643
+ ];
644
+ }
645
+
646
+
647
+ /**
648
+ * Draw a rectangle.
649
+ */
650
+ public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
651
+ {
652
+ if ($width !== 0 && $height !== 0) {
653
+ $this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
654
+ }
655
+ }
656
+
657
+
658
+ /**
659
+ * Draw a filled rectangle.
660
+ */
661
+ public function filledRectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
662
+ {
663
+ if ($width !== 0 && $height !== 0) {
664
+ $this->filledRectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
665
+ }
666
+ }
667
+
668
+
669
+ /**
670
+ * Saves image to the file. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9).
671
+ * @param ImageType::*|null $type
672
+ * @throws ImageException
673
+ */
674
+ public function save(string $file, ?int $quality = null, ?int $type = null): void
675
+ {
676
+ $type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
677
+ $this->output($type, $quality, $file);
678
+ }
679
+
680
+
681
+ /**
682
+ * Outputs image to string. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9).
683
+ * @param ImageType::* $type
684
+ */
685
+ public function toString(int $type = ImageType::JPEG, ?int $quality = null): string
686
+ {
687
+ return Helpers::capture(function () use ($type, $quality): void {
688
+ $this->output($type, $quality);
689
+ });
690
+ }
691
+
692
+
693
+ /**
694
+ * Outputs image to string.
695
+ */
696
+ public function __toString(): string
697
+ {
698
+ return $this->toString();
699
+ }
700
+
701
+
702
+ /**
703
+ * Outputs image to browser. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9).
704
+ * @param ImageType::* $type
705
+ * @throws ImageException
706
+ */
707
+ public function send(int $type = ImageType::JPEG, ?int $quality = null): void
708
+ {
709
+ header('Content-Type: ' . self::typeToMimeType($type));
710
+ $this->output($type, $quality);
711
+ }
712
+
713
+
714
+ /**
715
+ * Outputs image to browser or file.
716
+ * @param ImageType::* $type
717
+ * @throws ImageException
718
+ */
719
+ private function output(int $type, ?int $quality, ?string $file = null): void
720
+ {
721
+ switch ($type) {
722
+ case ImageType::JPEG:
723
+ $quality = $quality === null ? 85 : max(0, min(100, $quality));
724
+ $success = @imagejpeg($this->image, $file, $quality); // @ is escalated to exception
725
+ break;
726
+
727
+ case ImageType::PNG:
728
+ $quality = $quality === null ? 9 : max(0, min(9, $quality));
729
+ $success = @imagepng($this->image, $file, $quality); // @ is escalated to exception
730
+ break;
731
+
732
+ case ImageType::GIF:
733
+ $success = @imagegif($this->image, $file); // @ is escalated to exception
734
+ break;
735
+
736
+ case ImageType::WEBP:
737
+ $quality = $quality === null ? 80 : max(0, min(100, $quality));
738
+ $success = @imagewebp($this->image, $file, $quality); // @ is escalated to exception
739
+ break;
740
+
741
+ case ImageType::AVIF:
742
+ $quality = $quality === null ? 30 : max(0, min(100, $quality));
743
+ $success = @imageavif($this->image, $file, $quality); // @ is escalated to exception
744
+ break;
745
+
746
+ case ImageType::BMP:
747
+ $success = @imagebmp($this->image, $file); // @ is escalated to exception
748
+ break;
749
+
750
+ default:
751
+ throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
752
+ }
753
+
754
+ if (!$success) {
755
+ throw new ImageException(Helpers::getLastError() ?: 'Unknown error');
756
+ }
757
+ }
758
+
759
+
760
+ /**
761
+ * Call to undefined method.
762
+ * @throws Nette\MemberAccessException
763
+ */
764
+ public function __call(string $name, array $args): mixed
765
+ {
766
+ $function = 'image' . $name;
767
+ if (!function_exists($function)) {
768
+ ObjectHelpers::strictCall(static::class, $name);
769
+ }
770
+
771
+ foreach ($args as $key => $value) {
772
+ if ($value instanceof self) {
773
+ $args[$key] = $value->getImageResource();
774
+
775
+ } elseif ($value instanceof ImageColor || (is_array($value) && isset($value['red']))) {
776
+ $args[$key] = $this->resolveColor($value);
777
+ }
778
+ }
779
+
780
+ $res = $function($this->image, ...$args);
781
+ return $res instanceof \GdImage
782
+ ? $this->setImageResource($res)
783
+ : $res;
784
+ }
785
+
786
+
787
+ public function __clone()
788
+ {
789
+ ob_start(function () {});
790
+ imagepng($this->image, null, 0);
791
+ $this->setImageResource(imagecreatefromstring(ob_get_clean()));
792
+ }
793
+
794
+
795
+ private static function isPercent(int|string &$num): bool
796
+ {
797
+ if (is_string($num) && str_ends_with($num, '%')) {
798
+ $num = (float) substr($num, 0, -1);
799
+ return true;
800
+ } elseif (is_int($num) || $num === (string) (int) $num) {
801
+ $num = (int) $num;
802
+ return false;
803
+ }
804
+
805
+ throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given.");
806
+ }
807
+
808
+
809
+ /**
810
+ * Prevents serialization.
811
+ */
812
+ public function __sleep(): array
813
+ {
814
+ throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.');
815
+ }
816
+
817
+
818
+ public function resolveColor(ImageColor|array $color): int
819
+ {
820
+ $color = $color instanceof ImageColor ? $color->toRGBA() : array_values($color);
821
+ return imagecolorallocatealpha($this->image, ...$color) ?: imagecolorresolvealpha($this->image, ...$color);
822
+ }
823
+
824
+
825
+ private static function ensureExtension(): void
826
+ {
827
+ if (!extension_loaded('gd')) {
828
+ throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
829
+ }
830
+ }
831
+ }