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

nette / utils / 20848143243

09 Jan 2026 09:58AM UTC coverage: 93.264%. Remained the same
20848143243

push

github

dg
added CLAUDE.md

2063 of 2212 relevant lines covered (93.26%)

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 $affine, ?array $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 colorsForIndex(int $color)
45
 * @method int colorsTotal()
46
 * @method int colorTransparent(?int $color = null)
47
 * @method void convolution(array $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 = IMG_CROP_DEFAULT, 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 $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 ftText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array $options = [])
64
 * @method void gammaCorrect(float $inputgamma, float $outputgamma)
65
 * @method array 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 $points, ImageColor $color)
72
 * @method void paletteCopy(Image $source)
73
 * @method void paletteToTrueColor()
74
 * @method void polygon(array $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 = IMG_BILINEAR_FIXED)
80
 * @method void setBrush(Image $brush)
81
 * @method void setClip(int $x1, int $y1, int $x2, int $y2)
82
 * @method void setInterpolation(int $method = IMG_BILINEAR_FIXED)
83
 * @method void setPixel(int $x, int $y, ImageColor $color)
84
 * @method void setStyle(array $style)
85
 * @method void setThickness(int $thickness)
86
 * @method void setTile(Image $tile)
87
 * @method void trueColorToPalette(bool $dither, int $ncolors)
88
 * @method array ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontfile, string $text, array $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
         * @throws Nette\NotSupportedException if gd extension is not loaded
218
         */
219
        public static function fromBlank(int $width, int $height, ImageColor|array|null $color = null): static
1✔
220
        {
221
                self::ensureExtension();
1✔
222
                if ($width < 1 || $height < 1) {
1✔
223
                        throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.');
×
224
                }
225

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

233
                return $image;
1✔
234
        }
235

236

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

247

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

258

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

270
                return self::Formats[$type];
1✔
271
        }
272

273

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

286
                return $extensions[$extension];
1✔
287
        }
288

289

290
        /**
291
         * Returns the mime type for the given image type.
292
         * @param  ImageType::*  $type
293
         */
294
        public static function typeToMimeType(int $type): string
1✔
295
        {
296
                return 'image/' . self::typeToExtension($type);
1✔
297
        }
298

299

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

317

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

333

334
        /**
335
         * Wraps GD image.
336
         */
337
        public function __construct(\GdImage $image)
1✔
338
        {
339
                $this->setImageResource($image);
1✔
340
                imagesavealpha($image, true);
1✔
341
        }
1✔
342

343

344
        /**
345
         * Returns image width.
346
         * @return positive-int
347
         */
348
        public function getWidth(): int
349
        {
350
                return imagesx($this->image);
1✔
351
        }
352

353

354
        /**
355
         * Returns image height.
356
         * @return positive-int
357
         */
358
        public function getHeight(): int
359
        {
360
                return imagesy($this->image);
1✔
361
        }
362

363

364
        /**
365
         * Sets image resource.
366
         */
367
        protected function setImageResource(\GdImage $image): static
1✔
368
        {
369
                $this->image = $image;
1✔
370
                return $this;
1✔
371
        }
372

373

374
        /**
375
         * Returns image GD resource.
376
         */
377
        public function getImageResource(): \GdImage
378
        {
379
                return $this->image;
1✔
380
        }
381

382

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

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

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

412
                if ($width < 0 || $height < 0) {
1✔
413
                        imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL);
1✔
414
                }
415

416
                return $this;
1✔
417
        }
418

419

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

440
                if ($newHeight === null) {
1✔
441
                } elseif (self::isPercent($newHeight)) {
1✔
442
                        $newHeight = (int) round($srcHeight / 100 * abs($newHeight));
1✔
443
                        $mode |= empty($percents) ? 0 : self::Stretch;
1✔
444
                } else {
445
                        $newHeight = abs($newHeight);
1✔
446
                }
447

448
                if ($mode & self::Stretch) { // non-proportional
1✔
449
                        if (!$newWidth || !$newHeight) {
1✔
450
                                throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.');
×
451
                        }
452

453
                        if ($mode & self::ShrinkOnly) {
1✔
454
                                $newWidth = min($srcWidth, $newWidth);
1✔
455
                                $newHeight = min($srcHeight, $newHeight);
1✔
456
                        }
457
                } else {  // proportional
458
                        if (!$newWidth && !$newHeight) {
1✔
459
                                throw new Nette\InvalidArgumentException('At least width or height must be specified.');
×
460
                        }
461

462
                        $scale = [];
1✔
463
                        if ($newWidth > 0) { // fit width
1✔
464
                                $scale[] = $newWidth / $srcWidth;
1✔
465
                        }
466

467
                        if ($newHeight > 0) { // fit height
1✔
468
                                $scale[] = $newHeight / $srcHeight;
1✔
469
                        }
470

471
                        if ($mode & self::OrBigger) {
1✔
472
                                $scale = [max($scale)];
1✔
473
                        }
474

475
                        if ($mode & self::ShrinkOnly) {
1✔
476
                                $scale[] = 1;
1✔
477
                        }
478

479
                        $scale = min($scale);
1✔
480
                        $newWidth = (int) round($srcWidth * $scale);
1✔
481
                        $newHeight = (int) round($srcHeight * $scale);
1✔
482
                }
483

484
                return [max($newWidth, 1), max($newHeight, 1)];
1✔
485
        }
486

487

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

504
                return $this;
1✔
505
        }
506

507

508
        /**
509
         * Calculates dimensions of cutout in image. Arguments accepts pixels or percent.
510
         */
511
        public static function calculateCutout(
1✔
512
                int $srcWidth,
513
                int $srcHeight,
514
                int|string $left,
515
                int|string $top,
516
                int|string $newWidth,
517
                int|string $newHeight,
518
        ): array
519
        {
520
                if (self::isPercent($newWidth)) {
1✔
521
                        $newWidth = (int) round($srcWidth / 100 * $newWidth);
1✔
522
                }
523

524
                if (self::isPercent($newHeight)) {
1✔
525
                        $newHeight = (int) round($srcHeight / 100 * $newHeight);
1✔
526
                }
527

528
                if (self::isPercent($left)) {
1✔
529
                        $left = (int) round(($srcWidth - $newWidth) / 100 * $left);
1✔
530
                }
531

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

536
                if ($left < 0) {
1✔
537
                        $newWidth += $left;
×
538
                        $left = 0;
×
539
                }
540

541
                if ($top < 0) {
1✔
542
                        $newHeight += $top;
×
543
                        $top = 0;
×
544
                }
545

546
                $newWidth = min($newWidth, $srcWidth - $left);
1✔
547
                $newHeight = min($newHeight, $srcHeight - $top);
1✔
548
                return [$left, $top, $newWidth, $newHeight];
1✔
549
        }
550

551

552
        /**
553
         * Sharpens image a little bit.
554
         */
555
        public function sharpen(): static
556
        {
557
                imageconvolution($this->image, [ // my magic numbers ;)
×
558
                        [-1, -1, -1],
×
559
                        [-1, 24, -1],
560
                        [-1, -1, -1],
561
                ], 16, 0);
×
562
                return $this;
×
563
        }
564

565

566
        /**
567
         * Puts another image into this image. Left and top accepts pixels or percent.
568
         * @param  int<0, 100>  $opacity 0..100
569
         */
570
        public function place(self $image, int|string $left = 0, int|string $top = 0, int $opacity = 100): static
1✔
571
        {
572
                $opacity = max(0, min(100, $opacity));
1✔
573
                if ($opacity === 0) {
1✔
574
                        return $this;
1✔
575
                }
576

577
                $width = $image->getWidth();
1✔
578
                $height = $image->getHeight();
1✔
579

580
                if (self::isPercent($left)) {
1✔
581
                        $left = (int) round(($this->getWidth() - $width) / 100 * $left);
1✔
582
                }
583

584
                if (self::isPercent($top)) {
1✔
585
                        $top = (int) round(($this->getHeight() - $height) / 100 * $top);
1✔
586
                }
587

588
                $output = $input = $image->image;
1✔
589
                if ($opacity < 100) {
1✔
590
                        $tbl = [];
1✔
591
                        for ($i = 0; $i < 128; $i++) {
1✔
592
                                $tbl[$i] = round(127 - (127 - $i) * $opacity / 100);
1✔
593
                        }
594

595
                        $output = imagecreatetruecolor($width, $height);
1✔
596
                        imagealphablending($output, false);
1✔
597
                        if (!$image->isTrueColor()) {
1✔
598
                                $input = $output;
1✔
599
                                imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127));
1✔
600
                                imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height);
1✔
601
                        }
602

603
                        for ($x = 0; $x < $width; $x++) {
1✔
604
                                for ($y = 0; $y < $height; $y++) {
1✔
605
                                        $c = \imagecolorat($input, $x, $y);
1✔
606
                                        $c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24);
1✔
607
                                        \imagesetpixel($output, $x, $y, $c);
1✔
608
                                }
609
                        }
610

611
                        imagealphablending($output, true);
1✔
612
                }
613

614
                imagecopy(
1✔
615
                        $this->image,
1✔
616
                        $output,
617
                        $left,
618
                        $top,
619
                        0,
1✔
620
                        0,
1✔
621
                        $width,
622
                        $height,
623
                );
624
                return $this;
1✔
625
        }
626

627

628
        /**
629
         * Calculates the bounding box for a TrueType text. Returns keys left, top, width and height.
630
         */
631
        public static function calculateTextBox(
632
                string $text,
633
                string $fontFile,
634
                float $size,
635
                float $angle = 0,
636
                array $options = [],
637
        ): array
638
        {
639
                self::ensureExtension();
×
640
                $box = imagettfbbox($size, $angle, $fontFile, $text, $options);
×
641
                return [
642
                        'left' => $minX = min([$box[0], $box[2], $box[4], $box[6]]),
×
643
                        'top' => $minY = min([$box[1], $box[3], $box[5], $box[7]]),
×
644
                        'width' => max([$box[0], $box[2], $box[4], $box[6]]) - $minX + 1,
×
645
                        'height' => max([$box[1], $box[3], $box[5], $box[7]]) - $minY + 1,
×
646
                ];
647
        }
648

649

650
        /**
651
         * Draw a rectangle.
652
         */
653
        public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
1✔
654
        {
655
                if ($width !== 0 && $height !== 0) {
1✔
656
                        $this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
1✔
657
                }
658
        }
1✔
659

660

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

671

672
        /**
673
         * 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).
674
         * @param  ImageType::*|null  $type
675
         * @throws ImageException
676
         */
677
        public function save(string $file, ?int $quality = null, ?int $type = null): void
1✔
678
        {
679
                $type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
1✔
680
                $this->output($type, $quality, $file);
1✔
681
        }
1✔
682

683

684
        /**
685
         * 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).
686
         * @param  ImageType::*  $type
687
         */
688
        public function toString(int $type = ImageType::JPEG, ?int $quality = null): string
1✔
689
        {
690
                return Helpers::capture(function () use ($type, $quality): void {
1✔
691
                        $this->output($type, $quality);
1✔
692
                });
1✔
693
        }
694

695

696
        /**
697
         * Outputs image to string.
698
         */
699
        public function __toString(): string
700
        {
701
                return $this->toString();
1✔
702
        }
703

704

705
        /**
706
         * 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).
707
         * @param  ImageType::*  $type
708
         * @throws ImageException
709
         */
710
        public function send(int $type = ImageType::JPEG, ?int $quality = null): void
1✔
711
        {
712
                header('Content-Type: ' . self::typeToMimeType($type));
1✔
713
                $this->output($type, $quality);
1✔
714
        }
1✔
715

716

717
        /**
718
         * Outputs image to browser or file.
719
         * @param  ImageType::*  $type
720
         * @throws ImageException
721
         */
722
        private function output(int $type, ?int $quality, ?string $file = null): void
1✔
723
        {
724
                [$defQuality, $min, $max] = match ($type) {
1✔
725
                        ImageType::JPEG => [85, 0, 100],
1✔
726
                        ImageType::PNG => [9, 0, 9],
1✔
727
                        ImageType::GIF => [null, null, null],
1✔
728
                        ImageType::WEBP => [80, 0, 100],
1✔
729
                        ImageType::AVIF => [30, 0, 100],
1✔
730
                        ImageType::BMP => [null, null, null],
1✔
731
                        default => throw new Nette\InvalidArgumentException("Unsupported image type '$type'."),
1✔
732
                };
733

734
                $args = [$this->image, $file];
1✔
735
                if ($defQuality !== null) {
1✔
736
                        $args[] = $quality === null ? $defQuality : max($min, min($max, $quality));
1✔
737
                }
738

739
                Callback::invokeSafe('image' . self::Formats[$type], $args, function (string $message) use ($file): void {
1✔
740
                        if ($file !== null) {
1✔
741
                                @unlink($file);
1✔
742
                        }
743
                        throw new ImageException($message);
1✔
744
                });
1✔
745
        }
1✔
746

747

748
        /**
749
         * Call to undefined method.
750
         * @throws Nette\MemberAccessException
751
         */
752
        public function __call(string $name, array $args): mixed
1✔
753
        {
754
                $function = 'image' . $name;
1✔
755
                if (!function_exists($function)) {
1✔
756
                        ObjectHelpers::strictCall(static::class, $name);
1✔
757
                }
758

759
                foreach ($args as $key => $value) {
1✔
760
                        if ($value instanceof self) {
1✔
761
                                $args[$key] = $value->getImageResource();
1✔
762

763
                        } elseif ($value instanceof ImageColor || (is_array($value) && isset($value['red']))) {
1✔
764
                                $args[$key] = $this->resolveColor($value);
1✔
765
                        }
766
                }
767

768
                $res = $function($this->image, ...$args);
1✔
769
                return $res instanceof \GdImage
1✔
770
                        ? $this->setImageResource($res)
1✔
771
                        : $res;
1✔
772
        }
773

774

775
        public function __clone()
776
        {
777
                ob_start(fn() => '');
1✔
778
                imagepng($this->image, null, 0);
1✔
779
                $this->setImageResource(imagecreatefromstring(ob_get_clean()));
1✔
780
        }
1✔
781

782

783
        private static function isPercent(int|string &$num): bool
1✔
784
        {
785
                if (is_string($num) && str_ends_with($num, '%')) {
1✔
786
                        $num = (float) substr($num, 0, -1);
1✔
787
                        return true;
1✔
788
                } elseif (is_int($num) || $num === (string) (int) $num) {
1✔
789
                        $num = (int) $num;
1✔
790
                        return false;
1✔
791
                }
792

793
                throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given.");
×
794
        }
795

796

797
        /**
798
         * Prevents serialization.
799
         */
800
        public function __serialize(): array
801
        {
802
                throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.');
×
803
        }
804

805

806
        public function resolveColor(ImageColor|array $color): int
1✔
807
        {
808
                $color = $color instanceof ImageColor ? $color->toRGBA() : array_values($color);
1✔
809
                return imagecolorallocatealpha($this->image, ...$color) ?: imagecolorresolvealpha($this->image, ...$color);
1✔
810
        }
811

812

813
        private static function ensureExtension(): void
814
        {
815
                if (!extension_loaded('gd')) {
1✔
816
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
817
                }
818
        }
1✔
819
}
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