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

nette / utils / 14159925179

30 Mar 2025 09:02PM UTC coverage: 92.385%. Remained the same
14159925179

push

github

dg
Image: catches all errors during saving

13 of 16 new or added lines in 1 file covered. (81.25%)

3 existing lines in 1 file now uncovered.

2014 of 2180 relevant lines covered (92.39%)

0.92 hits per line

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

90.22
/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

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
1✔
149
        {
150
                return [
151
                        'red' => max(0, min(255, $red)),
1✔
152
                        'green' => max(0, min(255, $green)),
1✔
153
                        'blue' => max(0, min(255, $blue)),
1✔
154
                        'alpha' => max(0, min(127, $transparency)),
1✔
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
1✔
165
        {
166
                self::ensureExtension();
1✔
167
                $type = self::detectTypeFromFile($file);
1✔
168
                if (!$type) {
1✔
169
                        throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
1✔
170
                }
171

172
                return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__);
1✔
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
1✔
182
        {
183
                self::ensureExtension();
1✔
184
                $type = self::detectTypeFromString($s);
1✔
185
                if (!$type) {
1✔
186
                        throw new UnknownImageFileException('Unknown type of image.');
1✔
187
                }
188

189
                return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__);
1✔
190
        }
191

192

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

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

206
                return new static($res);
1✔
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
1✔
217
        {
218
                self::ensureExtension();
1✔
219
                if ($width < 1 || $height < 1) {
1✔
220
                        throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.');
×
221
                }
222

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

230
                return $image;
1✔
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
1✔
239
        {
240
                [$width, $height, $type] = @getimagesize($file); // @ - files smaller than 12 bytes causes read error
1✔
241
                return isset(self::Formats[$type]) ? $type : null;
1✔
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
1✔
250
        {
251
                [$width, $height, $type] = @getimagesizefromstring($s); // @ - strings smaller than 12 bytes causes read error
1✔
252
                return isset(self::Formats[$type]) ? $type : null;
1✔
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
1✔
262
        {
263
                if (!isset(self::Formats[$type])) {
1✔
264
                        throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
1✔
265
                }
266

267
                return self::Formats[$type];
1✔
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
1✔
276
        {
277
                $extensions = array_flip(self::Formats) + ['jpg' => ImageType::JPEG];
1✔
278
                $extension = strtolower($extension);
1✔
279
                if (!isset($extensions[$extension])) {
1✔
280
                        throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'.");
1✔
281
                }
282

283
                return $extensions[$extension];
1✔
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
1✔
292
        {
293
                return 'image/' . self::typeToExtension($type);
1✔
294
        }
295

296

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

314

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

330

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

340

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

350

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

360

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

370

371
        /**
372
         * Returns image GD resource.
373
         */
374
        public function getImageResource(): \GdImage
375
        {
376
                return $this->image;
1✔
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
1✔
385
        {
386
                if ($mode & self::Cover) {
1✔
387
                        return $this->resize($width, $height, self::OrBigger)->crop('50%', '50%', $width, $height);
1✔
388
                }
389

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

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

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

413
                return $this;
1✔
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(
1✔
422
                int $srcWidth,
423
                int $srcHeight,
424
                $newWidth,
425
                $newHeight,
426
                int $mode = self::OrSmaller,
427
        ): array
428
        {
429
                if ($newWidth === null) {
1✔
430
                } elseif (self::isPercent($newWidth)) {
1✔
431
                        $newWidth = (int) round($srcWidth / 100 * abs($newWidth));
1✔
432
                        $percents = true;
1✔
433
                } else {
434
                        $newWidth = abs($newWidth);
1✔
435
                }
436

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

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

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

459
                        $scale = [];
1✔
460
                        if ($newWidth > 0) { // fit width
1✔
461
                                $scale[] = $newWidth / $srcWidth;
1✔
462
                        }
463

464
                        if ($newHeight > 0) { // fit height
1✔
465
                                $scale[] = $newHeight / $srcHeight;
1✔
466
                        }
467

468
                        if ($mode & self::OrBigger) {
1✔
469
                                $scale = [max($scale)];
1✔
470
                        }
471

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

476
                        $scale = min($scale);
1✔
477
                        $newWidth = (int) round($srcWidth * $scale);
1✔
478
                        $newHeight = (int) round($srcHeight * $scale);
1✔
479
                }
480

481
                return [max($newWidth, 1), max($newHeight, 1)];
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
1✔
489
        {
490
                [$r['x'], $r['y'], $r['width'], $r['height']]
1✔
491
                        = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
1✔
492
                if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') {
1✔
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();
1✔
497
                        imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']);
1✔
498
                        $this->image = $newImage;
1✔
499
                }
500

501
                return $this;
1✔
502
        }
503

504

505
        /**
506
         * Calculates dimensions of cutout in image. Arguments accepts pixels or percent.
507
         */
508
        public static function calculateCutout(
1✔
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)) {
1✔
518
                        $newWidth = (int) round($srcWidth / 100 * $newWidth);
1✔
519
                }
520

521
                if (self::isPercent($newHeight)) {
1✔
522
                        $newHeight = (int) round($srcHeight / 100 * $newHeight);
1✔
523
                }
524

525
                if (self::isPercent($left)) {
1✔
526
                        $left = (int) round(($srcWidth - $newWidth) / 100 * $left);
1✔
527
                }
528

529
                if (self::isPercent($top)) {
1✔
530
                        $top = (int) round(($srcHeight - $newHeight) / 100 * $top);
1✔
531
                }
532

533
                if ($left < 0) {
1✔
534
                        $newWidth += $left;
×
535
                        $left = 0;
×
536
                }
537

538
                if ($top < 0) {
1✔
539
                        $newHeight += $top;
×
540
                        $top = 0;
×
541
                }
542

543
                $newWidth = min($newWidth, $srcWidth - $left);
1✔
544
                $newHeight = min($newHeight, $srcHeight - $top);
1✔
545
                return [$left, $top, $newWidth, $newHeight];
1✔
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
1✔
568
        {
569
                $opacity = max(0, min(100, $opacity));
1✔
570
                if ($opacity === 0) {
1✔
571
                        return $this;
1✔
572
                }
573

574
                $width = $image->getWidth();
1✔
575
                $height = $image->getHeight();
1✔
576

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

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

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

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

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

608
                        imagealphablending($output, true);
1✔
609
                }
610

611
                imagecopy(
1✔
612
                        $this->image,
1✔
613
                        $output,
614
                        $left,
615
                        $top,
616
                        0,
1✔
617
                        0,
1✔
618
                        $width,
619
                        $height,
620
                );
621
                return $this;
1✔
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
1✔
651
        {
652
                if ($width !== 0 && $height !== 0) {
1✔
653
                        $this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
1✔
654
                }
655
        }
1✔
656

657

658
        /**
659
         * Draw a filled rectangle.
660
         */
661
        public function filledRectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
1✔
662
        {
663
                if ($width !== 0 && $height !== 0) {
1✔
664
                        $this->filledRectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
1✔
665
                }
666
        }
1✔
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
1✔
675
        {
676
                $type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
1✔
677
                $this->output($type, $quality, $file);
1✔
678
        }
1✔
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
1✔
686
        {
687
                return Helpers::capture(function () use ($type, $quality): void {
1✔
688
                        $this->output($type, $quality);
1✔
689
                });
1✔
690
        }
691

692

693
        /**
694
         * Outputs image to string.
695
         */
696
        public function __toString(): string
697
        {
698
                return $this->toString();
1✔
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
1✔
708
        {
709
                header('Content-Type: ' . self::typeToMimeType($type));
1✔
710
                $this->output($type, $quality);
1✔
711
        }
1✔
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
1✔
720
        {
721
                [$defQuality, $min, $max] = match ($type) {
1✔
722
                        ImageType::JPEG => [85, 0, 100],
1✔
723
                        ImageType::PNG => [9, 0, 9],
1✔
724
                        ImageType::GIF => [null, null, null],
1✔
725
                        ImageType::WEBP => [80, 0, 100],
1✔
726
                        ImageType::AVIF => [30, 0, 100],
1✔
727
                        ImageType::BMP => [null, null, null],
1✔
728
                        default => throw new Nette\InvalidArgumentException("Unsupported image type '$type'."),
1✔
729
                };
730

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

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

744

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

756
                foreach ($args as $key => $value) {
1✔
757
                        if ($value instanceof self) {
1✔
758
                                $args[$key] = $value->getImageResource();
1✔
759

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

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

771

772
        public function __clone()
773
        {
774
                ob_start(function () {});
1✔
775
                imagepng($this->image, null, 0);
1✔
776
                $this->setImageResource(imagecreatefromstring(ob_get_clean()));
1✔
777
        }
1✔
778

779

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

UNCOV
790
                throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given.");
×
791
        }
792

793

794
        /**
795
         * Prevents serialization.
796
         */
797
        public function __sleep(): array
798
        {
UNCOV
799
                throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.');
×
800
        }
801

802

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

809

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