• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / utils / 21636962765

03 Feb 2026 03:39PM UTC coverage: 93.312% (+0.05%) from 93.264%
21636962765

push

github

dg
added CLAUDE.md

2065 of 2213 relevant lines covered (93.31%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.3
/src/Utils/Image.php
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
use function is_array, is_int, is_string;
14
use const IMG_BMP, IMG_FLIP_BOTH, IMG_FLIP_HORIZONTAL, IMG_FLIP_VERTICAL, IMG_GIF, IMG_JPG, IMG_PNG, IMG_WEBP, PATHINFO_EXTENSION;
15

16

17
/**
18
 * Basic manipulation with images. Supported types are JPEG, PNG, GIF, WEBP, AVIF and BMP.
19
 *
20
 * <code>
21
 * $image = Image::fromFile('nette.jpg');
22
 * $image->resize(150, 100);
23
 * $image->sharpen();
24
 * $image->send();
25
 * </code>
26
 *
27
 * @method Image affine(array<int, float|int> $affine, ?array{x: int, y: int, width: int, height: int} $clip = null)
28
 * @method void alphaBlending(bool $enable)
29
 * @method void antialias(bool $enable)
30
 * @method void arc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color)
31
 * @method int colorAllocate(int $red, int $green, int $blue)
32
 * @method int colorAllocateAlpha(int $red, int $green, int $blue, int $alpha)
33
 * @method int colorAt(int $x, int $y)
34
 * @method int colorClosest(int $red, int $green, int $blue)
35
 * @method int colorClosestAlpha(int $red, int $green, int $blue, int $alpha)
36
 * @method int colorClosestHWB(int $red, int $green, int $blue)
37
 * @method void colorDeallocate(int $color)
38
 * @method int colorExact(int $red, int $green, int $blue)
39
 * @method int colorExactAlpha(int $red, int $green, int $blue, int $alpha)
40
 * @method void colorMatch(Image $image2)
41
 * @method int colorResolve(int $red, int $green, int $blue)
42
 * @method int colorResolveAlpha(int $red, int $green, int $blue, int $alpha)
43
 * @method void colorSet(int $index, int $red, int $green, int $blue, int $alpha = 0)
44
 * @method array{red: int, green: int, blue: int, alpha: int} colorsForIndex(int $color)
45
 * @method int colorsTotal()
46
 * @method int colorTransparent(?int $color = null)
47
 * @method void convolution(array<int, array<int, float>> $matrix, float $div, float $offset)
48
 * @method void copy(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH)
49
 * @method void copyMerge(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)
50
 * @method void copyMergeGray(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)
51
 * @method void copyResampled(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)
52
 * @method void copyResized(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)
53
 * @method Image cropAuto(int $mode = 0, float $threshold = .5, ?ImageColor $color = null)
54
 * @method void ellipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color)
55
 * @method void fill(int $x, int $y, ImageColor $color)
56
 * @method void filledArc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color, int $style)
57
 * @method void filledEllipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color)
58
 * @method void filledPolygon(array<int, int> $points, ImageColor $color)
59
 * @method void filledRectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
60
 * @method void fillToBorder(int $x, int $y, ImageColor $borderColor, ImageColor $color)
61
 * @method void filter(int $filter, ...$args)
62
 * @method void flip(int $mode)
63
 * @method array<int, int> ftText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array<string, mixed> $options = [])
64
 * @method void gammaCorrect(float $inputgamma, float $outputgamma)
65
 * @method array{int, int, int, int} getClip()
66
 * @method int getInterpolation()
67
 * @method int interlace(?bool $enable = null)
68
 * @method bool isTrueColor()
69
 * @method void layerEffect(int $effect)
70
 * @method void line(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
71
 * @method void openPolygon(array<int, int> $points, ImageColor $color)
72
 * @method void paletteCopy(Image $source)
73
 * @method void paletteToTrueColor()
74
 * @method void polygon(array<int, int> $points, ImageColor $color)
75
 * @method void rectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
76
 * @method mixed resolution(?int $resolutionX = null, ?int $resolutionY = null)
77
 * @method Image rotate(float $angle, ImageColor $backgroundColor)
78
 * @method void saveAlpha(bool $enable)
79
 * @method Image scale(int $newWidth, int $newHeight = -1, int $mode = 3)
80
 * @method void setBrush(Image $brush)
81
 * @method void setClip(int $x1, int $y1, int $x2, int $y2)
82
 * @method void setInterpolation(int $method = 3)
83
 * @method void setPixel(int $x, int $y, ImageColor $color)
84
 * @method void setStyle(array<int, int> $style)
85
 * @method void setThickness(int $thickness)
86
 * @method void setTile(Image $tile)
87
 * @method void trueColorToPalette(bool $dither, int $ncolors)
88
 * @method array<int, int> ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontfile, string $text, array<string, mixed> $options = [])
89
 * @property-read positive-int $width
90
 * @property-read positive-int $height
91
 * @property-read \GdImage $imageResource
92
 */
93
class Image
94
{
95
        use Nette\SmartObject;
96

97
        /** Prevent from getting resized to a bigger size than the original */
98
        public const ShrinkOnly = 0b0001;
99

100
        /** Resizes to a specified width and height without keeping aspect ratio */
101
        public const Stretch = 0b0010;
102

103
        /** Resizes to fit into a specified width and height and preserves aspect ratio */
104
        public const OrSmaller = 0b0000;
105

106
        /** Resizes while bounding the smaller dimension to the specified width or height and preserves aspect ratio */
107
        public const OrBigger = 0b0100;
108

109
        /** Resizes to the smallest possible size to completely cover specified width and height and reserves aspect ratio */
110
        public const Cover = 0b1000;
111

112
        /** @deprecated use Image::ShrinkOnly */
113
        public const SHRINK_ONLY = self::ShrinkOnly;
114

115
        /** @deprecated use Image::Stretch */
116
        public const STRETCH = self::Stretch;
117

118
        /** @deprecated use Image::OrSmaller */
119
        public const FIT = self::OrSmaller;
120

121
        /** @deprecated use Image::OrBigger */
122
        public const FILL = self::OrBigger;
123

124
        /** @deprecated use Image::Cover */
125
        public const EXACT = self::Cover;
126

127
        /** @deprecated use Image::EmptyGIF */
128
        public const EMPTY_GIF = self::EmptyGIF;
129

130
        /** image types */
131
        public const
132
                JPEG = ImageType::JPEG,
133
                PNG = ImageType::PNG,
134
                GIF = ImageType::GIF,
135
                WEBP = ImageType::WEBP,
136
                AVIF = ImageType::AVIF,
137
                BMP = ImageType::BMP;
138

139
        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;";
140

141
        private const Formats = [ImageType::JPEG => 'jpeg', ImageType::PNG => 'png', ImageType::GIF => 'gif', ImageType::WEBP => 'webp', ImageType::AVIF => 'avif', ImageType::BMP => 'bmp'];
142

143
        private \GdImage $image;
144

145

146
        /**
147
         * Returns RGB color (0..255) and transparency (0..127).
148
         * @deprecated use ImageColor::rgb()
149
         * @return array{red: int, green: int, blue: int, alpha: int}
150
         */
151
        public static function rgb(int $red, int $green, int $blue, int $transparency = 0): array
1✔
152
        {
153
                return [
154
                        'red' => max(0, min(255, $red)),
1✔
155
                        'green' => max(0, min(255, $green)),
1✔
156
                        'blue' => max(0, min(255, $blue)),
1✔
157
                        'alpha' => max(0, min(127, $transparency)),
1✔
158
                ];
159
        }
160

161

162
        /**
163
         * Reads an image from a file and returns its type in $type.
164
         * @throws Nette\NotSupportedException if gd extension is not loaded
165
         * @throws UnknownImageFileException if file not found or file type is not known
166
         */
167
        public static function fromFile(string $file, ?int &$type = null): static
1✔
168
        {
169
                self::ensureExtension();
1✔
170
                $type = self::detectTypeFromFile($file);
1✔
171
                if (!$type) {
1✔
172
                        throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
1✔
173
                }
174

175
                return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__);
1✔
176
        }
177

178

179
        /**
180
         * Reads an image from a string and returns its type in $type.
181
         * @throws Nette\NotSupportedException if gd extension is not loaded
182
         * @throws ImageException
183
         */
184
        public static function fromString(string $s, ?int &$type = null): static
1✔
185
        {
186
                self::ensureExtension();
1✔
187
                $type = self::detectTypeFromString($s);
1✔
188
                if (!$type) {
1✔
189
                        throw new UnknownImageFileException('Unknown type of image.');
1✔
190
                }
191

192
                return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__);
1✔
193
        }
194

195

196
        private static function invokeSafe(string $func, string $arg, string $message, string $callee): static
1✔
197
        {
198
                $errors = [];
1✔
199
                $res = Callback::invokeSafe($func, [$arg], function (string $message) use (&$errors): void {
1✔
200
                        $errors[] = $message;
1✔
201
                });
1✔
202

203
                if (!$res) {
1✔
204
                        throw new ImageException($message . ' Errors: ' . implode(', ', $errors));
1✔
205
                } elseif ($errors) {
1✔
206
                        trigger_error($callee . '(): ' . implode(', ', $errors), E_USER_WARNING);
×
207
                }
208

209
                return new static($res);
1✔
210
        }
211

212

213
        /**
214
         * Creates a new true color image of the given dimensions. The default color is black.
215
         * @param  positive-int  $width
216
         * @param  positive-int  $height
217
         * @param  ImageColor|array{red: int, green: int, blue: int, alpha?: int}|null  $color
218
         * @throws Nette\NotSupportedException if gd extension is not loaded
219
         */
220
        public static function fromBlank(int $width, int $height, ImageColor|array|null $color = null): static
1✔
221
        {
222
                self::ensureExtension();
1✔
223
                if ($width < 1 || $height < 1) {
1✔
224
                        throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.');
×
225
                }
226

227
                $image = new static(imagecreatetruecolor($width, $height));
1✔
228
                if ($color) {
1✔
229
                        $image->alphaBlending(false);
1✔
230
                        $image->filledRectangle(0, 0, $width - 1, $height - 1, $color);
1✔
231
                        $image->alphaBlending(true);
1✔
232
                }
233

234
                return $image;
1✔
235
        }
236

237

238
        /**
239
         * Returns the type of image from file.
240
         * @param-out int|null  $width
241
         * @param-out int|null  $height
242
         * @return ImageType::*|null
243
         */
244
        public static function detectTypeFromFile(string $file, mixed &$width = null, mixed &$height = null): ?int
1✔
245
        {
246
                [$width, $height, $type] = Helpers::falseToNull(@getimagesize($file)); // @ - files smaller than 12 bytes causes read error
1✔
247
                return $type && isset(self::Formats[$type]) ? $type : null;
1✔
248
        }
249

250

251
        /**
252
         * Returns the type of image from string.
253
         * @param-out int|null  $width
254
         * @param-out int|null  $height
255
         * @return ImageType::*|null
256
         */
257
        public static function detectTypeFromString(string $s, mixed &$width = null, mixed &$height = null): ?int
1✔
258
        {
259
                [$width, $height, $type] = Helpers::falseToNull(@getimagesizefromstring($s)); // @ - strings smaller than 12 bytes causes read error
1✔
260
                return $type && isset(self::Formats[$type]) ? $type : null;
1✔
261
        }
262

263

264
        /**
265
         * Returns the file extension for the given image type.
266
         * @param  ImageType::*  $type
267
         * @return value-of<self::Formats>
268
         */
269
        public static function typeToExtension(int $type): string
1✔
270
        {
271
                if (!isset(self::Formats[$type])) {
1✔
272
                        throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
1✔
273
                }
274

275
                return self::Formats[$type];
1✔
276
        }
277

278

279
        /**
280
         * Returns the image type for given file extension.
281
         * @return ImageType::*
282
         */
283
        public static function extensionToType(string $extension): int
1✔
284
        {
285
                $extensions = array_flip(self::Formats) + ['jpg' => ImageType::JPEG];
1✔
286
                $extension = strtolower($extension);
1✔
287
                if (!isset($extensions[$extension])) {
1✔
288
                        throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'.");
1✔
289
                }
290

291
                return $extensions[$extension];
1✔
292
        }
293

294

295
        /**
296
         * Returns the mime type for the given image type.
297
         * @param  ImageType::*  $type
298
         */
299
        public static function typeToMimeType(int $type): string
1✔
300
        {
301
                return 'image/' . self::typeToExtension($type);
1✔
302
        }
303

304

305
        /**
306
         * @param  ImageType::*  $type
307
         */
308
        public static function isTypeSupported(int $type): bool
1✔
309
        {
310
                self::ensureExtension();
1✔
311
                return (bool) (imagetypes() & match ($type) {
1✔
312
                        ImageType::JPEG => IMG_JPG,
1✔
313
                        ImageType::PNG => IMG_PNG,
1✔
314
                        ImageType::GIF => IMG_GIF,
1✔
315
                        ImageType::WEBP => IMG_WEBP,
1✔
316
                        ImageType::AVIF => 256, // IMG_AVIF,
1✔
317
                        ImageType::BMP => IMG_BMP,
×
318
                        default => 0,
1✔
319
                });
320
        }
321

322

323
        /** @return  ImageType[] */
324
        public static function getSupportedTypes(): array
325
        {
326
                self::ensureExtension();
1✔
327
                $flag = imagetypes();
1✔
328
                return array_filter([
1✔
329
                        $flag & IMG_GIF ? ImageType::GIF : null,
1✔
330
                        $flag & IMG_JPG ? ImageType::JPEG : null,
1✔
331
                        $flag & IMG_PNG ? ImageType::PNG : null,
1✔
332
                        $flag & IMG_WEBP ? ImageType::WEBP : null,
1✔
333
                        $flag & 256 ? ImageType::AVIF : null, // IMG_AVIF
1✔
334
                        $flag & IMG_BMP ? ImageType::BMP : null,
1✔
335
                ]);
336
        }
337

338

339
        /**
340
         * Wraps GD image.
341
         */
342
        public function __construct(\GdImage $image)
1✔
343
        {
344
                $this->setImageResource($image);
1✔
345
                imagesavealpha($image, true);
1✔
346
        }
1✔
347

348

349
        /**
350
         * Returns image width.
351
         * @return positive-int
352
         */
353
        public function getWidth(): int
354
        {
355
                return imagesx($this->image);
1✔
356
        }
357

358

359
        /**
360
         * Returns image height.
361
         * @return positive-int
362
         */
363
        public function getHeight(): int
364
        {
365
                return imagesy($this->image);
1✔
366
        }
367

368

369
        /**
370
         * Sets image resource.
371
         */
372
        protected function setImageResource(\GdImage $image): static
1✔
373
        {
374
                $this->image = $image;
1✔
375
                return $this;
1✔
376
        }
377

378

379
        /**
380
         * Returns image GD resource.
381
         */
382
        public function getImageResource(): \GdImage
383
        {
384
                return $this->image;
1✔
385
        }
386

387

388
        /**
389
         * Scales an image. Width and height accept pixels or percent.
390
         * @param  int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly>  $mode
391
         */
392
        public function resize(int|string|null $width, int|string|null $height, int $mode = self::OrSmaller): static
1✔
393
        {
394
                if ($mode & self::Cover) {
1✔
395
                        return $this->resize($width, $height, self::OrBigger)->crop('50%', '50%', $width, $height);
1✔
396
                }
397

398
                [$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $mode);
1✔
399

400
                if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize
1✔
401
                        $newImage = static::fromBlank($newWidth, $newHeight, ImageColor::rgb(0, 0, 0, 0))->getImageResource();
1✔
402
                        imagecopyresampled(
1✔
403
                                $newImage,
1✔
404
                                $this->image,
1✔
405
                                0,
1✔
406
                                0,
1✔
407
                                0,
1✔
408
                                0,
1✔
409
                                $newWidth,
410
                                $newHeight,
411
                                $this->getWidth(),
1✔
412
                                $this->getHeight(),
1✔
413
                        );
414
                        $this->image = $newImage;
1✔
415
                }
416

417
                if ($width < 0 || $height < 0) {
1✔
418
                        imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL);
1✔
419
                }
420

421
                return $this;
1✔
422
        }
423

424

425
        /**
426
         * Calculates dimensions of resized image. Width and height accept pixels or percent.
427
         * @param  int|string|null  $newWidth
428
         * @param  int|string|null  $newHeight
429
         * @param  int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly>  $mode
430
         * @return array{int, int}
431
         */
432
        public static function calculateSize(
1✔
433
                int $srcWidth,
434
                int $srcHeight,
435
                $newWidth,
436
                $newHeight,
437
                int $mode = self::OrSmaller,
438
        ): array
439
        {
440
                if ($newWidth === null) {
1✔
441
                } elseif (self::isPercent($newWidth)) {
1✔
442
                        $newWidth = (int) round($srcWidth / 100 * abs($newWidth));
1✔
443
                        $percents = true;
1✔
444
                } else {
445
                        $newWidth = abs($newWidth);
1✔
446
                }
447

448
                if ($newHeight === null) {
1✔
449
                } elseif (self::isPercent($newHeight)) {
1✔
450
                        $newHeight = (int) round($srcHeight / 100 * abs($newHeight));
1✔
451
                        $mode |= empty($percents) ? 0 : self::Stretch;
1✔
452
                } else {
453
                        $newHeight = abs($newHeight);
1✔
454
                }
455

456
                if ($mode & self::Stretch) { // non-proportional
1✔
457
                        if (!$newWidth || !$newHeight) {
1✔
458
                                throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.');
×
459
                        }
460

461
                        if ($mode & self::ShrinkOnly) {
1✔
462
                                $newWidth = min($srcWidth, $newWidth);
1✔
463
                                $newHeight = min($srcHeight, $newHeight);
1✔
464
                        }
465
                } else {  // proportional
466
                        if (!$newWidth && !$newHeight) {
1✔
467
                                throw new Nette\InvalidArgumentException('At least width or height must be specified.');
×
468
                        }
469

470
                        $scale = [];
1✔
471
                        if ($newWidth > 0) { // fit width
1✔
472
                                $scale[] = $newWidth / $srcWidth;
1✔
473
                        }
474

475
                        if ($newHeight > 0) { // fit height
1✔
476
                                $scale[] = $newHeight / $srcHeight;
1✔
477
                        }
478

479
                        if ($mode & self::OrBigger) {
1✔
480
                                $scale = [max($scale)];
1✔
481
                        }
482

483
                        if ($mode & self::ShrinkOnly) {
1✔
484
                                $scale[] = 1;
1✔
485
                        }
486

487
                        $scale = min($scale);
1✔
488
                        $newWidth = (int) round($srcWidth * $scale);
1✔
489
                        $newHeight = (int) round($srcHeight * $scale);
1✔
490
                }
491

492
                return [max($newWidth, 1), max($newHeight, 1)];
1✔
493
        }
494

495

496
        /**
497
         * Crops image. Arguments accepts pixels or percent.
498
         */
499
        public function crop(int|string $left, int|string $top, int|string $width, int|string $height): static
1✔
500
        {
501
                [$r['x'], $r['y'], $r['width'], $r['height']]
1✔
502
                        = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
1✔
503
                if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') {
1✔
504
                        $this->image = imagecrop($this->image, $r);
×
505
                        imagesavealpha($this->image, true);
×
506
                } else {
507
                        $newImage = static::fromBlank($r['width'], $r['height'], ImageColor::rgb(0, 0, 0, 0))->getImageResource();
1✔
508
                        imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']);
1✔
509
                        $this->image = $newImage;
1✔
510
                }
511

512
                return $this;
1✔
513
        }
514

515

516
        /**
517
         * Calculates dimensions of cutout in image. Arguments accepts pixels or percent.
518
         * @return array{int, int, int, int}
519
         */
520
        public static function calculateCutout(
1✔
521
                int $srcWidth,
522
                int $srcHeight,
523
                int|string $left,
524
                int|string $top,
525
                int|string $newWidth,
526
                int|string $newHeight,
527
        ): array
528
        {
529
                if (self::isPercent($newWidth)) {
1✔
530
                        $newWidth = (int) round($srcWidth / 100 * $newWidth);
1✔
531
                }
532

533
                if (self::isPercent($newHeight)) {
1✔
534
                        $newHeight = (int) round($srcHeight / 100 * $newHeight);
1✔
535
                }
536

537
                if (self::isPercent($left)) {
1✔
538
                        $left = (int) round(($srcWidth - $newWidth) / 100 * $left);
1✔
539
                }
540

541
                if (self::isPercent($top)) {
1✔
542
                        $top = (int) round(($srcHeight - $newHeight) / 100 * $top);
1✔
543
                }
544

545
                if ($left < 0) {
1✔
546
                        $newWidth += $left;
×
547
                        $left = 0;
×
548
                }
549

550
                if ($top < 0) {
1✔
551
                        $newHeight += $top;
×
552
                        $top = 0;
×
553
                }
554

555
                $newWidth = min($newWidth, $srcWidth - $left);
1✔
556
                $newHeight = min($newHeight, $srcHeight - $top);
1✔
557
                return [$left, $top, $newWidth, $newHeight];
1✔
558
        }
559

560

561
        /**
562
         * Sharpens image a little bit.
563
         */
564
        public function sharpen(): static
565
        {
566
                imageconvolution($this->image, [ // my magic numbers ;)
×
567
                        [-1, -1, -1],
×
568
                        [-1, 24, -1],
569
                        [-1, -1, -1],
570
                ], 16, 0);
×
571
                return $this;
×
572
        }
573

574

575
        /**
576
         * Puts another image into this image. Left and top accepts pixels or percent.
577
         * @param  int<0, 100>  $opacity 0..100
578
         */
579
        public function place(self $image, int|string $left = 0, int|string $top = 0, int $opacity = 100): static
1✔
580
        {
581
                $opacity = max(0, min(100, $opacity));
1✔
582
                if ($opacity === 0) {
1✔
583
                        return $this;
1✔
584
                }
585

586
                $width = $image->getWidth();
1✔
587
                $height = $image->getHeight();
1✔
588

589
                if (self::isPercent($left)) {
1✔
590
                        $left = (int) round(($this->getWidth() - $width) / 100 * $left);
1✔
591
                }
592

593
                if (self::isPercent($top)) {
1✔
594
                        $top = (int) round(($this->getHeight() - $height) / 100 * $top);
1✔
595
                }
596

597
                $output = $input = $image->image;
1✔
598
                if ($opacity < 100) {
1✔
599
                        $tbl = [];
1✔
600
                        for ($i = 0; $i < 128; $i++) {
1✔
601
                                $tbl[$i] = round(127 - (127 - $i) * $opacity / 100);
1✔
602
                        }
603

604
                        $output = imagecreatetruecolor($width, $height);
1✔
605
                        imagealphablending($output, false);
1✔
606
                        if (!$image->isTrueColor()) {
1✔
607
                                $input = $output;
1✔
608
                                imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127));
1✔
609
                                imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height);
1✔
610
                        }
611

612
                        for ($x = 0; $x < $width; $x++) {
1✔
613
                                for ($y = 0; $y < $height; $y++) {
1✔
614
                                        $c = \imagecolorat($input, $x, $y);
1✔
615
                                        $c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24);
1✔
616
                                        \imagesetpixel($output, $x, $y, $c);
1✔
617
                                }
618
                        }
619

620
                        imagealphablending($output, true);
1✔
621
                }
622

623
                imagecopy(
1✔
624
                        $this->image,
1✔
625
                        $output,
626
                        $left,
627
                        $top,
628
                        0,
1✔
629
                        0,
1✔
630
                        $width,
631
                        $height,
632
                );
633
                return $this;
1✔
634
        }
635

636

637
        /**
638
         * Calculates the bounding box for a TrueType text. Returns keys left, top, width and height.
639
         * @param  array<string, mixed>  $options
640
         * @return array{left: int, top: int, width: int, height: int}
641
         */
642
        public static function calculateTextBox(
643
                string $text,
644
                string $fontFile,
645
                float $size,
646
                float $angle = 0,
647
                array $options = [],
648
        ): array
649
        {
650
                self::ensureExtension();
×
651
                $box = imagettfbbox($size, $angle, $fontFile, $text, $options);
×
652
                return [
653
                        'left' => $minX = min([$box[0], $box[2], $box[4], $box[6]]),
×
654
                        'top' => $minY = min([$box[1], $box[3], $box[5], $box[7]]),
×
655
                        'width' => max([$box[0], $box[2], $box[4], $box[6]]) - $minX + 1,
×
656
                        'height' => max([$box[1], $box[3], $box[5], $box[7]]) - $minY + 1,
×
657
                ];
658
        }
659

660

661
        /**
662
         * Draw a rectangle.
663
         */
664
        public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
1✔
665
        {
666
                if ($width !== 0 && $height !== 0) {
1✔
667
                        $this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
1✔
668
                }
669
        }
1✔
670

671

672
        /**
673
         * Draw a filled rectangle.
674
         */
675
        public function filledRectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
1✔
676
        {
677
                if ($width !== 0 && $height !== 0) {
1✔
678
                        $this->filledRectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
1✔
679
                }
680
        }
1✔
681

682

683
        /**
684
         * 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).
685
         * @param  ImageType::*|null  $type
686
         * @throws ImageException
687
         */
688
        public function save(string $file, ?int $quality = null, ?int $type = null): void
1✔
689
        {
690
                $type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
1✔
691
                $this->output($type, $quality, $file);
1✔
692
        }
1✔
693

694

695
        /**
696
         * 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).
697
         * @param  ImageType::*  $type
698
         */
699
        public function toString(int $type = ImageType::JPEG, ?int $quality = null): string
1✔
700
        {
701
                return Helpers::capture(function () use ($type, $quality): void {
1✔
702
                        $this->output($type, $quality);
1✔
703
                });
1✔
704
        }
705

706

707
        /**
708
         * Outputs image to string.
709
         */
710
        public function __toString(): string
711
        {
712
                return $this->toString();
1✔
713
        }
714

715

716
        /**
717
         * 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).
718
         * @param  ImageType::*  $type
719
         * @throws ImageException
720
         */
721
        public function send(int $type = ImageType::JPEG, ?int $quality = null): void
1✔
722
        {
723
                header('Content-Type: ' . self::typeToMimeType($type));
1✔
724
                $this->output($type, $quality);
1✔
725
        }
1✔
726

727

728
        /**
729
         * Outputs image to browser or file.
730
         * @param  ImageType::*  $type
731
         * @throws ImageException
732
         */
733
        private function output(int $type, ?int $quality, ?string $file = null): void
1✔
734
        {
735
                [$defQuality, $min, $max] = match ($type) {
1✔
736
                        ImageType::JPEG => [85, 0, 100],
1✔
737
                        ImageType::PNG => [9, 0, 9],
1✔
738
                        ImageType::GIF => [null, null, null],
1✔
739
                        ImageType::WEBP => [80, 0, 100],
1✔
740
                        ImageType::AVIF => [30, 0, 100],
1✔
741
                        ImageType::BMP => [null, null, null],
1✔
742
                        default => throw new Nette\InvalidArgumentException("Unsupported image type '$type'."),
1✔
743
                };
744

745
                $args = [$this->image, $file];
1✔
746
                if ($defQuality !== null) {
1✔
747
                        $args[] = $quality === null ? $defQuality : max($min, min($max, $quality));
1✔
748
                }
749

750
                Callback::invokeSafe('image' . self::Formats[$type], $args, function (string $message) use ($file): void {
1✔
751
                        if ($file !== null) {
1✔
752
                                @unlink($file);
1✔
753
                        }
754
                        throw new ImageException($message);
1✔
755
                });
1✔
756
        }
1✔
757

758

759
        /**
760
         * Call to undefined method.
761
         * @param  array<mixed>  $args
762
         * @throws Nette\MemberAccessException
763
         */
764
        public function __call(string $name, array $args): mixed
1✔
765
        {
766
                $function = 'image' . $name;
1✔
767
                if (!function_exists($function)) {
1✔
768
                        ObjectHelpers::strictCall(static::class, $name);
1✔
769
                }
770

771
                foreach ($args as $key => $value) {
1✔
772
                        if ($value instanceof self) {
1✔
773
                                $args[$key] = $value->getImageResource();
1✔
774

775
                        } elseif ($value instanceof ImageColor || (is_array($value) && isset($value['red']))) {
1✔
776
                                $args[$key] = $this->resolveColor($value);
1✔
777
                        }
778
                }
779

780
                $res = $function($this->image, ...$args);
1✔
781
                return $res instanceof \GdImage
1✔
782
                        ? $this->setImageResource($res)
1✔
783
                        : $res;
1✔
784
        }
785

786

787
        public function __clone()
788
        {
789
                ob_start(fn() => '');
1✔
790
                imagepng($this->image, null, 0);
1✔
791
                $this->setImageResource(imagecreatefromstring(ob_get_clean()));
1✔
792
        }
1✔
793

794

795
        private static function isPercent(int|string &$num): bool
1✔
796
        {
797
                if (is_string($num) && str_ends_with($num, '%')) {
1✔
798
                        $num = (float) substr($num, 0, -1);
1✔
799
                        return true;
1✔
800
                } elseif (is_int($num) || $num === (string) (int) $num) {
1✔
801
                        $num = (int) $num;
1✔
802
                        return false;
1✔
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 __serialize(): array
813
        {
814
                throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.');
×
815
        }
816

817

818
        /**
819
         * @param  ImageColor|array{red: int, green: int, blue: int, alpha?: int}  $color
820
         */
821
        public function resolveColor(ImageColor|array $color): int
1✔
822
        {
823
                $color = $color instanceof ImageColor ? $color->toRGBA() : array_values($color + ['alpha' => 0]);
1✔
824
                return imagecolorallocatealpha($this->image, ...$color) ?: imagecolorresolvealpha($this->image, ...$color);
1✔
825
        }
826

827

828
        private static function ensureExtension(): void
829
        {
830
                if (!extension_loaded('gd')) {
1✔
831
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
832
                }
833
        }
1✔
834
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc