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

nette / utils / 6685761332

29 Oct 2023 09:02PM UTC coverage: 91.905%. First build
6685761332

push

github

dg
added Image::rectangleWH(), filledRectangleWH(), calculateTextBox()

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

1896 of 2063 relevant lines covered (91.9%)

0.92 hits per line

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

88.69
/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
                if (!extension_loaded('gd')) {
1✔
167
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
168
                }
169

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
                if (!extension_loaded('gd')) {
1✔
187
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
188
                }
189

190
                $type = self::detectTypeFromString($s);
1✔
191
                if (!$type) {
1✔
192
                        throw new UnknownImageFileException('Unknown type of image.');
1✔
193
                }
194

195
                return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__);
1✔
196
        }
197

198

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

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

212
                return new static($res);
1✔
213
        }
214

215

216
        /**
217
         * Creates a new true color image of the given dimensions. The default color is black.
218
         * @param  positive-int  $width
219
         * @param  positive-int  $height
220
         * @throws Nette\NotSupportedException if gd extension is not loaded
221
         */
222
        public static function fromBlank(int $width, int $height, ImageColor|array|null $color = null): static
1✔
223
        {
224
                if (!extension_loaded('gd')) {
1✔
225
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
226
                }
227

228
                if ($width < 1 || $height < 1) {
1✔
229
                        throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.');
×
230
                }
231

232
                $image = new static(imagecreatetruecolor($width, $height));
1✔
233
                if ($color) {
1✔
234
                        $image->alphablending(false);
1✔
235
                        $image->filledrectangle(0, 0, $width - 1, $height - 1, $color);
1✔
236
                        $image->alphablending(true);
1✔
237
                }
238

239
                return $image;
1✔
240
        }
241

242

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

253

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

264

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

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

279

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

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

295

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

305

306
        /**
307
         * @param  ImageType::*  $type
308
         */
309
        public static function isTypeSupported(int $type): bool
1✔
310
        {
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
        /**
324
         * Wraps GD image.
325
         */
326
        public function __construct(\GdImage $image)
1✔
327
        {
328
                $this->setImageResource($image);
1✔
329
                imagesavealpha($image, true);
1✔
330
        }
1✔
331

332

333
        /**
334
         * Returns image width.
335
         * @return positive-int
336
         */
337
        public function getWidth(): int
338
        {
339
                return imagesx($this->image);
1✔
340
        }
341

342

343
        /**
344
         * Returns image height.
345
         * @return positive-int
346
         */
347
        public function getHeight(): int
348
        {
349
                return imagesy($this->image);
1✔
350
        }
351

352

353
        /**
354
         * Sets image resource.
355
         */
356
        protected function setImageResource(\GdImage $image): static
1✔
357
        {
358
                $this->image = $image;
1✔
359
                return $this;
1✔
360
        }
361

362

363
        /**
364
         * Returns image GD resource.
365
         */
366
        public function getImageResource(): \GdImage
367
        {
368
                return $this->image;
1✔
369
        }
370

371

372
        /**
373
         * Scales an image. Width and height accept pixels or percent.
374
         * @param  int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly>  $mode
375
         */
376
        public function resize(int|string|null $width, int|string|null $height, int $mode = self::OrSmaller): static
1✔
377
        {
378
                if ($mode & self::Cover) {
1✔
379
                        return $this->resize($width, $height, self::OrBigger)->crop('50%', '50%', $width, $height);
1✔
380
                }
381

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

384
                if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize
1✔
385
                        $newImage = static::fromBlank($newWidth, $newHeight, ImageColor::rgb(0, 0, 0, 0))->getImageResource();
1✔
386
                        imagecopyresampled(
1✔
387
                                $newImage,
1✔
388
                                $this->image,
1✔
389
                                0,
1✔
390
                                0,
1✔
391
                                0,
1✔
392
                                0,
1✔
393
                                $newWidth,
394
                                $newHeight,
395
                                $this->getWidth(),
1✔
396
                                $this->getHeight(),
1✔
397
                        );
398
                        $this->image = $newImage;
1✔
399
                }
400

401
                if ($width < 0 || $height < 0) {
1✔
402
                        imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL);
1✔
403
                }
404

405
                return $this;
1✔
406
        }
407

408

409
        /**
410
         * Calculates dimensions of resized image. Width and height accept pixels or percent.
411
         * @param  int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly>  $mode
412
         */
413
        public static function calculateSize(
1✔
414
                int $srcWidth,
415
                int $srcHeight,
416
                $newWidth,
417
                $newHeight,
418
                int $mode = self::OrSmaller,
419
        ): array
420
        {
421
                if ($newWidth === null) {
1✔
422
                } elseif (self::isPercent($newWidth)) {
1✔
423
                        $newWidth = (int) round($srcWidth / 100 * abs($newWidth));
1✔
424
                        $percents = true;
1✔
425
                } else {
426
                        $newWidth = abs($newWidth);
1✔
427
                }
428

429
                if ($newHeight === null) {
1✔
430
                } elseif (self::isPercent($newHeight)) {
1✔
431
                        $newHeight = (int) round($srcHeight / 100 * abs($newHeight));
1✔
432
                        $mode |= empty($percents) ? 0 : self::Stretch;
1✔
433
                } else {
434
                        $newHeight = abs($newHeight);
1✔
435
                }
436

437
                if ($mode & self::Stretch) { // non-proportional
1✔
438
                        if (!$newWidth || !$newHeight) {
1✔
439
                                throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.');
×
440
                        }
441

442
                        if ($mode & self::ShrinkOnly) {
1✔
443
                                $newWidth = min($srcWidth, $newWidth);
1✔
444
                                $newHeight = min($srcHeight, $newHeight);
1✔
445
                        }
446
                } else {  // proportional
447
                        if (!$newWidth && !$newHeight) {
1✔
448
                                throw new Nette\InvalidArgumentException('At least width or height must be specified.');
×
449
                        }
450

451
                        $scale = [];
1✔
452
                        if ($newWidth > 0) { // fit width
1✔
453
                                $scale[] = $newWidth / $srcWidth;
1✔
454
                        }
455

456
                        if ($newHeight > 0) { // fit height
1✔
457
                                $scale[] = $newHeight / $srcHeight;
1✔
458
                        }
459

460
                        if ($mode & self::OrBigger) {
1✔
461
                                $scale = [max($scale)];
1✔
462
                        }
463

464
                        if ($mode & self::ShrinkOnly) {
1✔
465
                                $scale[] = 1;
1✔
466
                        }
467

468
                        $scale = min($scale);
1✔
469
                        $newWidth = (int) round($srcWidth * $scale);
1✔
470
                        $newHeight = (int) round($srcHeight * $scale);
1✔
471
                }
472

473
                return [max($newWidth, 1), max($newHeight, 1)];
1✔
474
        }
475

476

477
        /**
478
         * Crops image. Arguments accepts pixels or percent.
479
         */
480
        public function crop(int|string $left, int|string $top, int|string $width, int|string $height): static
1✔
481
        {
482
                [$r['x'], $r['y'], $r['width'], $r['height']]
1✔
483
                        = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
1✔
484
                if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') {
1✔
485
                        $this->image = imagecrop($this->image, $r);
×
486
                        imagesavealpha($this->image, true);
×
487
                } else {
488
                        $newImage = static::fromBlank($r['width'], $r['height'], ImageColor::rgb(0, 0, 0, 0))->getImageResource();
1✔
489
                        imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']);
1✔
490
                        $this->image = $newImage;
1✔
491
                }
492

493
                return $this;
1✔
494
        }
495

496

497
        /**
498
         * Calculates dimensions of cutout in image. Arguments accepts pixels or percent.
499
         */
500
        public static function calculateCutout(
1✔
501
                int $srcWidth,
502
                int $srcHeight,
503
                int|string $left,
504
                int|string $top,
505
                int|string $newWidth,
506
                int|string $newHeight,
507
        ): array
508
        {
509
                if (self::isPercent($newWidth)) {
1✔
510
                        $newWidth = (int) round($srcWidth / 100 * $newWidth);
1✔
511
                }
512

513
                if (self::isPercent($newHeight)) {
1✔
514
                        $newHeight = (int) round($srcHeight / 100 * $newHeight);
1✔
515
                }
516

517
                if (self::isPercent($left)) {
1✔
518
                        $left = (int) round(($srcWidth - $newWidth) / 100 * $left);
1✔
519
                }
520

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

525
                if ($left < 0) {
1✔
526
                        $newWidth += $left;
×
527
                        $left = 0;
×
528
                }
529

530
                if ($top < 0) {
1✔
531
                        $newHeight += $top;
×
532
                        $top = 0;
×
533
                }
534

535
                $newWidth = min($newWidth, $srcWidth - $left);
1✔
536
                $newHeight = min($newHeight, $srcHeight - $top);
1✔
537
                return [$left, $top, $newWidth, $newHeight];
1✔
538
        }
539

540

541
        /**
542
         * Sharpens image a little bit.
543
         */
544
        public function sharpen(): static
545
        {
546
                imageconvolution($this->image, [ // my magic numbers ;)
×
547
                        [-1, -1, -1],
×
548
                        [-1, 24, -1],
549
                        [-1, -1, -1],
550
                ], 16, 0);
×
551
                return $this;
×
552
        }
553

554

555
        /**
556
         * Puts another image into this image. Left and top accepts pixels or percent.
557
         * @param  int<0, 100>  $opacity 0..100
558
         */
559
        public function place(self $image, int|string $left = 0, int|string $top = 0, int $opacity = 100): static
1✔
560
        {
561
                $opacity = max(0, min(100, $opacity));
1✔
562
                if ($opacity === 0) {
1✔
563
                        return $this;
1✔
564
                }
565

566
                $width = $image->getWidth();
1✔
567
                $height = $image->getHeight();
1✔
568

569
                if (self::isPercent($left)) {
1✔
570
                        $left = (int) round(($this->getWidth() - $width) / 100 * $left);
1✔
571
                }
572

573
                if (self::isPercent($top)) {
1✔
574
                        $top = (int) round(($this->getHeight() - $height) / 100 * $top);
1✔
575
                }
576

577
                $output = $input = $image->image;
1✔
578
                if ($opacity < 100) {
1✔
579
                        $tbl = [];
1✔
580
                        for ($i = 0; $i < 128; $i++) {
1✔
581
                                $tbl[$i] = round(127 - (127 - $i) * $opacity / 100);
1✔
582
                        }
583

584
                        $output = imagecreatetruecolor($width, $height);
1✔
585
                        imagealphablending($output, false);
1✔
586
                        if (!$image->isTrueColor()) {
1✔
587
                                $input = $output;
1✔
588
                                imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127));
1✔
589
                                imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height);
1✔
590
                        }
591

592
                        for ($x = 0; $x < $width; $x++) {
1✔
593
                                for ($y = 0; $y < $height; $y++) {
1✔
594
                                        $c = \imagecolorat($input, $x, $y);
1✔
595
                                        $c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24);
1✔
596
                                        \imagesetpixel($output, $x, $y, $c);
1✔
597
                                }
598
                        }
599

600
                        imagealphablending($output, true);
1✔
601
                }
602

603
                imagecopy(
1✔
604
                        $this->image,
1✔
605
                        $output,
606
                        $left,
607
                        $top,
608
                        0,
1✔
609
                        0,
1✔
610
                        $width,
611
                        $height,
612
                );
613
                return $this;
1✔
614
        }
615

616

617
        /**
618
         * Calculates the bounding box for a TrueType text. Returns keys left, top, width and height.
619
         */
620
        public static function calculateTextBox(
621
                string $text,
622
                string $fontFile,
623
                float $size,
624
                float $angle = 0,
625
                array $options = [],
626
        ): array
627
        {
628
                $box = imagettfbbox($size, $angle, $fontFile, $text, $options);
×
629
                return [
630
                        'left' => $minX = min([$box[0], $box[2], $box[4], $box[6]]),
×
631
                        'top' => $minY = min([$box[1], $box[3], $box[5], $box[7]]),
×
632
                        'width' => max([$box[0], $box[2], $box[4], $box[6]]) - $minX + 1,
×
633
                        'height' => max([$box[1], $box[3], $box[5], $box[7]]) - $minY + 1,
×
634
                ];
635
        }
636

637

638
        /**
639
         * Draw a rectangle.
640
         */
641
        public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
1✔
642
        {
643
                if ($width !== 0 && $height !== 0) {
1✔
644
                        $this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
1✔
645
                }
646
        }
1✔
647

648

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

659

660
        /**
661
         * 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).
662
         * @param  ImageType::*|null  $type
663
         * @throws ImageException
664
         */
665
        public function save(string $file, ?int $quality = null, ?int $type = null): void
1✔
666
        {
667
                $type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
1✔
668
                $this->output($type, $quality, $file);
1✔
669
        }
1✔
670

671

672
        /**
673
         * 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).
674
         * @param  ImageType::*  $type
675
         */
676
        public function toString(int $type = ImageType::JPEG, ?int $quality = null): string
1✔
677
        {
678
                return Helpers::capture(function () use ($type, $quality): void {
1✔
679
                        $this->output($type, $quality);
1✔
680
                });
1✔
681
        }
682

683

684
        /**
685
         * Outputs image to string.
686
         */
687
        public function __toString(): string
688
        {
689
                return $this->toString();
1✔
690
        }
691

692

693
        /**
694
         * 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).
695
         * @param  ImageType::*  $type
696
         * @throws ImageException
697
         */
698
        public function send(int $type = ImageType::JPEG, ?int $quality = null): void
1✔
699
        {
700
                header('Content-Type: ' . self::typeToMimeType($type));
1✔
701
                $this->output($type, $quality);
1✔
702
        }
1✔
703

704

705
        /**
706
         * Outputs image to browser or file.
707
         * @param  ImageType::*  $type
708
         * @throws ImageException
709
         */
710
        private function output(int $type, ?int $quality, ?string $file = null): void
1✔
711
        {
712
                switch ($type) {
713
                        case ImageType::JPEG:
1✔
714
                                $quality = $quality === null ? 85 : max(0, min(100, $quality));
1✔
715
                                $success = @imagejpeg($this->image, $file, $quality); // @ is escalated to exception
1✔
716
                                break;
1✔
717

718
                        case ImageType::PNG:
1✔
719
                                $quality = $quality === null ? 9 : max(0, min(9, $quality));
1✔
720
                                $success = @imagepng($this->image, $file, $quality); // @ is escalated to exception
1✔
721
                                break;
1✔
722

723
                        case ImageType::GIF:
1✔
724
                                $success = @imagegif($this->image, $file); // @ is escalated to exception
×
725
                                break;
×
726

727
                        case ImageType::WEBP:
1✔
728
                                $quality = $quality === null ? 80 : max(0, min(100, $quality));
1✔
729
                                $success = @imagewebp($this->image, $file, $quality); // @ is escalated to exception
1✔
730
                                break;
1✔
731

732
                        case ImageType::AVIF:
1✔
733
                                $quality = $quality === null ? 30 : max(0, min(100, $quality));
×
734
                                $success = @imageavif($this->image, $file, $quality); // @ is escalated to exception
×
735
                                break;
×
736

737
                        case ImageType::BMP:
1✔
738
                                $success = @imagebmp($this->image, $file); // @ is escalated to exception
1✔
739
                                break;
1✔
740

741
                        default:
742
                                throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
1✔
743
                }
744

745
                if (!$success) {
1✔
746
                        throw new ImageException(Helpers::getLastError() ?: 'Unknown error');
×
747
                }
748
        }
1✔
749

750

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

762
                foreach ($args as $key => $value) {
1✔
763
                        if ($value instanceof self) {
1✔
764
                                $args[$key] = $value->getImageResource();
1✔
765

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

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

777

778
        public function __clone()
779
        {
780
                ob_start(function () {});
1✔
781
                imagepng($this->image, null, 0);
1✔
782
                $this->setImageResource(imagecreatefromstring(ob_get_clean()));
1✔
783
        }
1✔
784

785

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

796
                throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given.");
×
797
        }
798

799

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

808

809
        public function resolveColor(ImageColor|array $color): int
1✔
810
        {
811
                $color = $color instanceof ImageColor ? $color->toRGBA() : array_values($color);
1✔
812
                return imagecolorallocatealpha($this->image, ...$color) ?: imagecolorresolvealpha($this->image, ...$color);
1✔
813
        }
814
}
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