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

nette / utils / 5707056869

pending completion
5707056869

push

github

dg
support for PHP 8.3

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

1580 of 1753 relevant lines covered (90.13%)

0.9 hits per line

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

88.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

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 array affineMatrixConcat(array $m1, array $m2)
27
 * @method array affineMatrixGet(int $type, mixed $options = null)
28
 * @method void alphaBlending(bool $on)
29
 * @method void antialias(bool $on)
30
 * @method void arc($x, $y, $w, $h, $start, $end, $color)
31
 * @method void char(int $font, $x, $y, string $char, $color)
32
 * @method void charUp(int $font, $x, $y, string $char, $color)
33
 * @method int colorAllocate($red, $green, $blue)
34
 * @method int colorAllocateAlpha($red, $green, $blue, $alpha)
35
 * @method int colorAt($x, $y)
36
 * @method int colorClosest($red, $green, $blue)
37
 * @method int colorClosestAlpha($red, $green, $blue, $alpha)
38
 * @method int colorClosestHWB($red, $green, $blue)
39
 * @method void colorDeallocate($color)
40
 * @method int colorExact($red, $green, $blue)
41
 * @method int colorExactAlpha($red, $green, $blue, $alpha)
42
 * @method void colorMatch(Image $image2)
43
 * @method int colorResolve($red, $green, $blue)
44
 * @method int colorResolveAlpha($red, $green, $blue, $alpha)
45
 * @method void colorSet($index, $red, $green, $blue)
46
 * @method array colorsForIndex($index)
47
 * @method int colorsTotal()
48
 * @method int colorTransparent($color = null)
49
 * @method void convolution(array $matrix, float $div, float $offset)
50
 * @method void copy(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH)
51
 * @method void copyMerge(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH, $opacity)
52
 * @method void copyMergeGray(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH, $opacity)
53
 * @method void copyResampled(Image $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH)
54
 * @method void copyResized(Image $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH)
55
 * @method Image cropAuto(int $mode = -1, float $threshold = .5, int $color = -1)
56
 * @method void ellipse($cx, $cy, $w, $h, $color)
57
 * @method void fill($x, $y, $color)
58
 * @method void filledArc($cx, $cy, $w, $h, $s, $e, $color, $style)
59
 * @method void filledEllipse($cx, $cy, $w, $h, $color)
60
 * @method void filledPolygon(array $points, $numPoints, $color)
61
 * @method void filledRectangle($x1, $y1, $x2, $y2, $color)
62
 * @method void fillToBorder($x, $y, $border, $color)
63
 * @method void filter($filtertype)
64
 * @method void flip(int $mode)
65
 * @method array ftText($size, $angle, $x, $y, $col, string $fontFile, string $text, array $extrainfo = null)
66
 * @method void gammaCorrect(float $inputgamma, float $outputgamma)
67
 * @method array getClip()
68
 * @method int interlace($interlace = null)
69
 * @method bool isTrueColor()
70
 * @method void layerEffect($effect)
71
 * @method void line($x1, $y1, $x2, $y2, $color)
72
 * @method void openPolygon(array $points, int $num_points, int $color)
73
 * @method void paletteCopy(Image $source)
74
 * @method void paletteToTrueColor()
75
 * @method void polygon(array $points, $numPoints, $color)
76
 * @method array psText(string $text, $font, $size, $color, $backgroundColor, $x, $y, $space = null, $tightness = null, float $angle = null, $antialiasSteps = null)
77
 * @method void rectangle($x1, $y1, $x2, $y2, $col)
78
 * @method mixed resolution(int $res_x = null, int $res_y = null)
79
 * @method Image rotate(float $angle, $backgroundColor)
80
 * @method void saveAlpha(bool $saveflag)
81
 * @method Image scale(int $newWidth, int $newHeight = -1, int $mode = IMG_BILINEAR_FIXED)
82
 * @method void setBrush(Image $brush)
83
 * @method void setClip(int $x1, int $y1, int $x2, int $y2)
84
 * @method void setInterpolation(int $method = IMG_BILINEAR_FIXED)
85
 * @method void setPixel($x, $y, $color)
86
 * @method void setStyle(array $style)
87
 * @method void setThickness($thickness)
88
 * @method void setTile(Image $tile)
89
 * @method void string($font, $x, $y, string $s, $col)
90
 * @method void stringUp($font, $x, $y, string $s, $col)
91
 * @method void trueColorToPalette(bool $dither, $ncolors)
92
 * @method array ttfText($size, $angle, $x, $y, $color, string $fontfile, string $text)
93
 * @property-read positive-int $width
94
 * @property-read positive-int $height
95
 * @property-read resource|\GdImage $imageResource
96
 */
97
class Image
98
{
99
        use Nette\SmartObject;
100

101
        /** Prevent from getting resized to a bigger size than the original */
102
        public const SHRINK_ONLY = 0b0001;
103

104
        /** Resizes to a specified width and height without keeping aspect ratio */
105
        public const STRETCH = 0b0010;
106

107
        /** Resizes to fit into a specified width and height and preserves aspect ratio */
108
        public const FIT = 0b0000;
109

110
        /** Resizes while bounding the smaller dimension to the specified width or height and preserves aspect ratio */
111
        public const FILL = 0b0100;
112

113
        /** Resizes to the smallest possible size to completely cover specified width and height and reserves aspect ratio */
114
        public const EXACT = 0b1000;
115

116
        /** image types */
117
        public const
118
                JPEG = IMAGETYPE_JPEG,
119
                PNG = IMAGETYPE_PNG,
120
                GIF = IMAGETYPE_GIF,
121
                WEBP = IMAGETYPE_WEBP,
122
                AVIF = 19, // IMAGETYPE_AVIF,
123
                BMP = IMAGETYPE_BMP;
124

125
        public const EMPTY_GIF = "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;";
126

127
        private const Formats = [self::JPEG => 'jpeg', self::PNG => 'png', self::GIF => 'gif', self::WEBP => 'webp', self::AVIF => 'avif', self::BMP => 'bmp'];
128

129
        /** @var resource|\GdImage */
130
        private $image;
131

132

133
        /**
134
         * Returns RGB color (0..255) and transparency (0..127).
135
         */
136
        public static function rgb(int $red, int $green, int $blue, int $transparency = 0): array
1✔
137
        {
138
                return [
139
                        'red' => max(0, min(255, $red)),
1✔
140
                        'green' => max(0, min(255, $green)),
1✔
141
                        'blue' => max(0, min(255, $blue)),
1✔
142
                        'alpha' => max(0, min(127, $transparency)),
1✔
143
                ];
144
        }
145

146

147
        /**
148
         * Reads an image from a file and returns its type in $type.
149
         * @throws Nette\NotSupportedException if gd extension is not loaded
150
         * @throws UnknownImageFileException if file not found or file type is not known
151
         * @return static
152
         */
153
        public static function fromFile(string $file, ?int &$type = null)
1✔
154
        {
155
                if (!extension_loaded('gd')) {
1✔
156
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
157
                }
158

159
                $type = self::detectTypeFromFile($file);
1✔
160
                if (!$type) {
1✔
161
                        throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
1✔
162
                }
163

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

167

168
        /**
169
         * Reads an image from a string and returns its type in $type.
170
         * @return static
171
         * @throws Nette\NotSupportedException if gd extension is not loaded
172
         * @throws ImageException
173
         */
174
        public static function fromString(string $s, ?int &$type = null)
1✔
175
        {
176
                if (!extension_loaded('gd')) {
1✔
177
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
178
                }
179

180
                $type = self::detectTypeFromString($s);
1✔
181
                if (!$type) {
1✔
182
                        throw new UnknownImageFileException('Unknown type of image.');
1✔
183
                }
184

185
                return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__);
1✔
186
        }
187

188

189
        private static function invokeSafe(string $func, string $arg, string $message, string $callee): self
1✔
190
        {
191
                $errors = [];
1✔
192
                $res = Callback::invokeSafe($func, [$arg], function (string $message) use (&$errors): void {
1✔
193
                        $errors[] = $message;
1✔
194
                });
1✔
195

196
                if (!$res) {
1✔
197
                        throw new ImageException($message . ' Errors: ' . implode(', ', $errors));
1✔
198
                } elseif ($errors) {
1✔
199
                        trigger_error($callee . '(): ' . implode(', ', $errors), E_USER_WARNING);
×
200
                }
201

202
                return new static($res);
1✔
203
        }
204

205

206
        /**
207
         * Creates a new true color image of the given dimensions. The default color is black.
208
         * @param  positive-int  $width
209
         * @param  positive-int  $height
210
         * @return static
211
         * @throws Nette\NotSupportedException if gd extension is not loaded
212
         */
213
        public static function fromBlank(int $width, int $height, ?array $color = null)
1✔
214
        {
215
                if (!extension_loaded('gd')) {
1✔
216
                        throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
×
217
                }
218

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 = imagecreatetruecolor($width, $height);
1✔
224
                if ($color) {
1✔
225
                        $color += ['alpha' => 0];
1✔
226
                        $color = imagecolorresolvealpha($image, $color['red'], $color['green'], $color['blue'], $color['alpha']);
1✔
227
                        imagealphablending($image, false);
1✔
228
                        imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $color);
1✔
229
                        imagealphablending($image, true);
1✔
230
                }
231

232
                return new static($image);
1✔
233
        }
234

235

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

245

246
        /**
247
         * Returns the type of image from string.
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::XXX` constant.
258
         */
259
        public static function typeToExtension(int $type): string
1✔
260
        {
261
                if (!isset(self::Formats[$type])) {
1✔
262
                        throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
1✔
263
                }
264

265
                return self::Formats[$type];
1✔
266
        }
267

268

269
        /**
270
         * Returns the `Image::XXX` constant for given file extension.
271
         */
272
        public static function extensionToType(string $extension): int
1✔
273
        {
274
                $extensions = array_flip(self::Formats) + ['jpg' => self::JPEG];
1✔
275
                $extension = strtolower($extension);
1✔
276
                if (!isset($extensions[$extension])) {
1✔
277
                        throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'.");
1✔
278
                }
279

280
                return $extensions[$extension];
1✔
281
        }
282

283

284
        /**
285
         * Returns the mime type for the given `Image::XXX` constant.
286
         */
287
        public static function typeToMimeType(int $type): string
1✔
288
        {
289
                return 'image/' . self::typeToExtension($type);
1✔
290
        }
291

292

293
        /**
294
         * Wraps GD image.
295
         * @param  resource|\GdImage  $image
296
         */
297
        public function __construct($image)
298
        {
299
                $this->setImageResource($image);
1✔
300
                imagesavealpha($image, true);
1✔
301
        }
1✔
302

303

304
        /**
305
         * Returns image width.
306
         * @return positive-int
307
         */
308
        public function getWidth(): int
309
        {
310
                return imagesx($this->image);
1✔
311
        }
312

313

314
        /**
315
         * Returns image height.
316
         * @return positive-int
317
         */
318
        public function getHeight(): int
319
        {
320
                return imagesy($this->image);
1✔
321
        }
322

323

324
        /**
325
         * Sets image resource.
326
         * @param  resource|\GdImage  $image
327
         * @return static
328
         */
329
        protected function setImageResource($image)
330
        {
331
                if (!$image instanceof \GdImage && !(is_resource($image) && get_resource_type($image) === 'gd')) {
1✔
332
                        throw new Nette\InvalidArgumentException('Image is not valid.');
×
333
                }
334

335
                $this->image = $image;
1✔
336
                return $this;
1✔
337
        }
338

339

340
        /**
341
         * Returns image GD resource.
342
         * @return resource|\GdImage
343
         */
344
        public function getImageResource()
345
        {
346
                return $this->image;
1✔
347
        }
348

349

350
        /**
351
         * Scales an image.
352
         * @param  int|string|null  $width in pixels or percent
353
         * @param  int|string|null  $height in pixels or percent
354
         * @return static
355
         */
356
        public function resize($width, $height, int $flags = self::FIT)
1✔
357
        {
358
                if ($flags & self::EXACT) {
1✔
359
                        return $this->resize($width, $height, self::FILL)->crop('50%', '50%', $width, $height);
1✔
360
                }
361

362
                [$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $flags);
1✔
363

364
                if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize
1✔
365
                        $newImage = static::fromBlank($newWidth, $newHeight, self::rgb(0, 0, 0, 127))->getImageResource();
1✔
366
                        imagecopyresampled(
1✔
367
                                $newImage,
1✔
368
                                $this->image,
1✔
369
                                0,
1✔
370
                                0,
1✔
371
                                0,
1✔
372
                                0,
1✔
373
                                $newWidth,
374
                                $newHeight,
375
                                $this->getWidth(),
1✔
376
                                $this->getHeight()
1✔
377
                        );
378
                        $this->image = $newImage;
1✔
379
                }
380

381
                if ($width < 0 || $height < 0) {
1✔
382
                        imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL);
1✔
383
                }
384

385
                return $this;
1✔
386
        }
387

388

389
        /**
390
         * Calculates dimensions of resized image.
391
         * @param  int|string|null  $newWidth in pixels or percent
392
         * @param  int|string|null  $newHeight in pixels or percent
393
         */
394
        public static function calculateSize(
1✔
395
                int $srcWidth,
396
                int $srcHeight,
397
                $newWidth,
398
                $newHeight,
399
                int $flags = self::FIT
400
        ): array
401
        {
402
                if ($newWidth === null) {
1✔
403
                } elseif (self::isPercent($newWidth)) {
1✔
404
                        $newWidth = (int) round($srcWidth / 100 * abs($newWidth));
1✔
405
                        $percents = true;
1✔
406
                } else {
407
                        $newWidth = abs($newWidth);
1✔
408
                }
409

410
                if ($newHeight === null) {
1✔
411
                } elseif (self::isPercent($newHeight)) {
1✔
412
                        $newHeight = (int) round($srcHeight / 100 * abs($newHeight));
1✔
413
                        $flags |= empty($percents) ? 0 : self::STRETCH;
1✔
414
                } else {
415
                        $newHeight = abs($newHeight);
1✔
416
                }
417

418
                if ($flags & self::STRETCH) { // non-proportional
1✔
419
                        if (!$newWidth || !$newHeight) {
1✔
420
                                throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.');
×
421
                        }
422

423
                        if ($flags & self::SHRINK_ONLY) {
1✔
424
                                $newWidth = (int) round($srcWidth * min(1, $newWidth / $srcWidth));
1✔
425
                                $newHeight = (int) round($srcHeight * min(1, $newHeight / $srcHeight));
1✔
426
                        }
427
                } else {  // proportional
428
                        if (!$newWidth && !$newHeight) {
1✔
429
                                throw new Nette\InvalidArgumentException('At least width or height must be specified.');
×
430
                        }
431

432
                        $scale = [];
1✔
433
                        if ($newWidth > 0) { // fit width
1✔
434
                                $scale[] = $newWidth / $srcWidth;
1✔
435
                        }
436

437
                        if ($newHeight > 0) { // fit height
1✔
438
                                $scale[] = $newHeight / $srcHeight;
1✔
439
                        }
440

441
                        if ($flags & self::FILL) {
1✔
442
                                $scale = [max($scale)];
1✔
443
                        }
444

445
                        if ($flags & self::SHRINK_ONLY) {
1✔
446
                                $scale[] = 1;
1✔
447
                        }
448

449
                        $scale = min($scale);
1✔
450
                        $newWidth = (int) round($srcWidth * $scale);
1✔
451
                        $newHeight = (int) round($srcHeight * $scale);
1✔
452
                }
453

454
                return [max($newWidth, 1), max($newHeight, 1)];
1✔
455
        }
456

457

458
        /**
459
         * Crops image.
460
         * @param  int|string  $left in pixels or percent
461
         * @param  int|string  $top in pixels or percent
462
         * @param  int|string  $width in pixels or percent
463
         * @param  int|string  $height in pixels or percent
464
         * @return static
465
         */
466
        public function crop($left, $top, $width, $height)
467
        {
468
                [$r['x'], $r['y'], $r['width'], $r['height']]
1✔
469
                        = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
1✔
470
                if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') {
1✔
471
                        $this->image = imagecrop($this->image, $r);
×
472
                        imagesavealpha($this->image, true);
×
473
                } else {
474
                        $newImage = static::fromBlank($r['width'], $r['height'], self::RGB(0, 0, 0, 127))->getImageResource();
1✔
475
                        imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']);
1✔
476
                        $this->image = $newImage;
1✔
477
                }
478

479
                return $this;
1✔
480
        }
481

482

483
        /**
484
         * Calculates dimensions of cutout in image.
485
         * @param  int|string  $left in pixels or percent
486
         * @param  int|string  $top in pixels or percent
487
         * @param  int|string  $newWidth in pixels or percent
488
         * @param  int|string  $newHeight in pixels or percent
489
         */
490
        public static function calculateCutout(int $srcWidth, int $srcHeight, $left, $top, $newWidth, $newHeight): array
1✔
491
        {
492
                if (self::isPercent($newWidth)) {
1✔
493
                        $newWidth = (int) round($srcWidth / 100 * $newWidth);
1✔
494
                }
495

496
                if (self::isPercent($newHeight)) {
1✔
497
                        $newHeight = (int) round($srcHeight / 100 * $newHeight);
1✔
498
                }
499

500
                if (self::isPercent($left)) {
1✔
501
                        $left = (int) round(($srcWidth - $newWidth) / 100 * $left);
1✔
502
                }
503

504
                if (self::isPercent($top)) {
1✔
505
                        $top = (int) round(($srcHeight - $newHeight) / 100 * $top);
1✔
506
                }
507

508
                if ($left < 0) {
1✔
509
                        $newWidth += $left;
×
510
                        $left = 0;
×
511
                }
512

513
                if ($top < 0) {
1✔
514
                        $newHeight += $top;
×
515
                        $top = 0;
×
516
                }
517

518
                $newWidth = min($newWidth, $srcWidth - $left);
1✔
519
                $newHeight = min($newHeight, $srcHeight - $top);
1✔
520
                return [$left, $top, $newWidth, $newHeight];
1✔
521
        }
522

523

524
        /**
525
         * Sharpens image a little bit.
526
         * @return static
527
         */
528
        public function sharpen()
529
        {
530
                imageconvolution($this->image, [ // my magic numbers ;)
×
531
                        [-1, -1, -1],
×
532
                        [-1, 24, -1],
533
                        [-1, -1, -1],
534
                ], 16, 0);
×
535
                return $this;
×
536
        }
537

538

539
        /**
540
         * Puts another image into this image.
541
         * @param  int|string  $left in pixels or percent
542
         * @param  int|string  $top in pixels or percent
543
         * @param  int<0, 100>  $opacity 0..100
544
         * @return static
545
         */
546
        public function place(self $image, $left = 0, $top = 0, int $opacity = 100)
1✔
547
        {
548
                $opacity = max(0, min(100, $opacity));
1✔
549
                if ($opacity === 0) {
1✔
550
                        return $this;
1✔
551
                }
552

553
                $width = $image->getWidth();
1✔
554
                $height = $image->getHeight();
1✔
555

556
                if (self::isPercent($left)) {
1✔
557
                        $left = (int) round(($this->getWidth() - $width) / 100 * $left);
1✔
558
                }
559

560
                if (self::isPercent($top)) {
1✔
561
                        $top = (int) round(($this->getHeight() - $height) / 100 * $top);
1✔
562
                }
563

564
                $output = $input = $image->image;
1✔
565
                if ($opacity < 100) {
1✔
566
                        $tbl = [];
1✔
567
                        for ($i = 0; $i < 128; $i++) {
1✔
568
                                $tbl[$i] = round(127 - (127 - $i) * $opacity / 100);
1✔
569
                        }
570

571
                        $output = imagecreatetruecolor($width, $height);
1✔
572
                        imagealphablending($output, false);
1✔
573
                        if (!$image->isTrueColor()) {
1✔
574
                                $input = $output;
1✔
575
                                imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127));
1✔
576
                                imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height);
1✔
577
                        }
578

579
                        for ($x = 0; $x < $width; $x++) {
1✔
580
                                for ($y = 0; $y < $height; $y++) {
1✔
581
                                        $c = \imagecolorat($input, $x, $y);
1✔
582
                                        $c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24);
1✔
583
                                        \imagesetpixel($output, $x, $y, $c);
1✔
584
                                }
585
                        }
586

587
                        imagealphablending($output, true);
1✔
588
                }
589

590
                imagecopy(
1✔
591
                        $this->image,
1✔
592
                        $output,
593
                        $left,
594
                        $top,
595
                        0,
1✔
596
                        0,
1✔
597
                        $width,
598
                        $height
599
                );
600
                return $this;
1✔
601
        }
602

603

604
        /**
605
         * 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).
606
         * @throws ImageException
607
         */
608
        public function save(string $file, ?int $quality = null, ?int $type = null): void
1✔
609
        {
610
                $type = $type ?? self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
1✔
611
                $this->output($type, $quality, $file);
1✔
612
        }
1✔
613

614

615
        /**
616
         * 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).
617
         */
618
        public function toString(int $type = self::JPEG, ?int $quality = null): string
1✔
619
        {
620
                return Helpers::capture(function () use ($type, $quality) {
1✔
621
                        $this->output($type, $quality);
1✔
622
                });
1✔
623
        }
624

625

626
        /**
627
         * Outputs image to string.
628
         */
629
        public function __toString(): string
630
        {
631
                try {
632
                        return $this->toString();
1✔
633
                } catch (\Throwable $e) {
×
634
                        if (func_num_args() || PHP_VERSION_ID >= 70400) {
×
635
                                throw $e;
×
636
                        }
637

638
                        trigger_error('Exception in ' . __METHOD__ . "(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}", E_USER_ERROR);
×
639
                        return '';
×
640
                }
641
        }
642

643

644
        /**
645
         * 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).
646
         * @throws ImageException
647
         */
648
        public function send(int $type = self::JPEG, ?int $quality = null): void
1✔
649
        {
650
                header('Content-Type: ' . self::typeToMimeType($type));
1✔
651
                $this->output($type, $quality);
1✔
652
        }
1✔
653

654

655
        /**
656
         * Outputs image to browser or file.
657
         * @throws ImageException
658
         */
659
        private function output(int $type, ?int $quality, ?string $file = null): void
1✔
660
        {
661
                switch ($type) {
662
                        case self::JPEG:
1✔
663
                                $quality = $quality === null ? 85 : max(0, min(100, $quality));
1✔
664
                                $success = @imagejpeg($this->image, $file, $quality); // @ is escalated to exception
1✔
665
                                break;
1✔
666

667
                        case self::PNG:
1✔
668
                                $quality = $quality === null ? 9 : max(0, min(9, $quality));
1✔
669
                                $success = @imagepng($this->image, $file, $quality); // @ is escalated to exception
1✔
670
                                break;
1✔
671

672
                        case self::GIF:
1✔
673
                                $success = @imagegif($this->image, $file); // @ is escalated to exception
×
674
                                break;
×
675

676
                        case self::WEBP:
1✔
677
                                $quality = $quality === null ? 80 : max(0, min(100, $quality));
1✔
678
                                $success = @imagewebp($this->image, $file, $quality); // @ is escalated to exception
1✔
679
                                break;
1✔
680

681
                        case self::AVIF:
1✔
682
                                $quality = $quality === null ? 30 : max(0, min(100, $quality));
×
683
                                $success = @imageavif($this->image, $file, $quality); // @ is escalated to exception
×
684
                                break;
×
685

686
                        case self::BMP:
1✔
687
                                $success = @imagebmp($this->image, $file); // @ is escalated to exception
1✔
688
                                break;
1✔
689

690
                        default:
691
                                throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
1✔
692
                }
693

694
                if (!$success) {
1✔
695
                        throw new ImageException(Helpers::getLastError() ?: 'Unknown error');
×
696
                }
697
        }
1✔
698

699

700
        /**
701
         * Call to undefined method.
702
         * @return mixed
703
         * @throws Nette\MemberAccessException
704
         */
705
        public function __call(string $name, array $args)
1✔
706
        {
707
                $function = 'image' . $name;
1✔
708
                if (!function_exists($function)) {
1✔
709
                        ObjectHelpers::strictCall(static::class, $name);
1✔
710
                }
711

712
                foreach ($args as $key => $value) {
1✔
713
                        if ($value instanceof self) {
1✔
714
                                $args[$key] = $value->getImageResource();
1✔
715

716
                        } elseif (is_array($value) && isset($value['red'])) { // rgb
1✔
717
                                $args[$key] = imagecolorallocatealpha(
1✔
718
                                        $this->image,
1✔
719
                                        $value['red'],
1✔
720
                                        $value['green'],
1✔
721
                                        $value['blue'],
1✔
722
                                        $value['alpha']
1✔
723
                                ) ?: imagecolorresolvealpha(
1✔
724
                                        $this->image,
1✔
725
                                        $value['red'],
1✔
726
                                        $value['green'],
1✔
727
                                        $value['blue'],
1✔
728
                                        $value['alpha']
1✔
729
                                );
730
                        }
731
                }
732

733
                $res = $function($this->image, ...$args);
1✔
734
                return $res instanceof \GdImage || (is_resource($res) && get_resource_type($res) === 'gd')
1✔
735
                        ? $this->setImageResource($res)
1✔
736
                        : $res;
1✔
737
        }
738

739

740
        public function __clone()
741
        {
742
                ob_start(function () {});
1✔
743
                imagepng($this->image, null, 0);
1✔
744
                $this->setImageResource(imagecreatefromstring(ob_get_clean()));
1✔
745
        }
1✔
746

747

748
        /**
749
         * @param  int|string  $num in pixels or percent
750
         */
751
        private static function isPercent(&$num): bool
752
        {
753
                if (is_string($num) && substr($num, -1) === '%') {
1✔
754
                        $num = (float) substr($num, 0, -1);
1✔
755
                        return true;
1✔
756
                } elseif (is_int($num) || $num === (string) (int) $num) {
1✔
757
                        $num = (int) $num;
1✔
758
                        return false;
1✔
759
                }
760

761
                throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given.");
×
762
        }
763

764

765
        /**
766
         * Prevents serialization.
767
         */
768
        public function __sleep(): array
769
        {
770
                throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.');
×
771
        }
772
}
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