Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 150 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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 int $width
94
 * @property-read int $height
95
 * @property-read resource|\GdImage $imageResource
96
 */
97
class Image
98
{
99
	use Nette\SmartObject;
100
 
101
	/** {@link resize()} only shrinks images */
102
	public const SHRINK_ONLY = 0b0001;
103
 
104
	/** {@link resize()} will ignore aspect ratio */
105
	public const STRETCH = 0b0010;
106
 
107
	/** {@link resize()} fits in given area so its dimensions are less than or equal to the required dimensions */
108
	public const FIT = 0b0000;
109
 
110
	/** {@link resize()} fills given area so its dimensions are greater than or equal to the required dimensions */
111
	public const FILL = 0b0100;
112
 
113
	/** {@link resize()} fills given area exactly */
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
137
	{
138
		return [
139
			'red' => max(0, min(255, $red)),
140
			'green' => max(0, min(255, $green)),
141
			'blue' => max(0, min(255, $blue)),
142
			'alpha' => max(0, min(127, $transparency)),
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)
154
	{
155
		if (!extension_loaded('gd')) {
156
			throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
157
		}
158
 
159
		$type = self::detectTypeFromFile($file);
160
		if (!$type) {
161
			throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
162
		}
163
 
164
		return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__);
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)
175
	{
176
		if (!extension_loaded('gd')) {
177
			throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
178
		}
179
 
180
		$type = self::detectTypeFromString($s);
181
		if (!$type) {
182
			throw new UnknownImageFileException('Unknown type of image.');
183
		}
184
 
185
		return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__);
186
	}
187
 
188
 
189
	private static function invokeSafe(string $func, string $arg, string $message, string $callee): self
190
	{
191
		$errors = [];
192
		$res = Callback::invokeSafe($func, [$arg], function (string $message) use (&$errors): void {
193
			$errors[] = $message;
194
		});
195
 
196
		if (!$res) {
197
			throw new ImageException($message . ' Errors: ' . implode(', ', $errors));
198
		} elseif ($errors) {
199
			trigger_error($callee . '(): ' . implode(', ', $errors), E_USER_WARNING);
200
		}
201
 
202
		return new static($res);
203
	}
204
 
205
 
206
	/**
207
	 * Creates a new true color image of the given dimensions. The default color is black.
208
	 * @return static
209
	 * @throws Nette\NotSupportedException if gd extension is not loaded
210
	 */
211
	public static function fromBlank(int $width, int $height, ?array $color = null)
212
	{
213
		if (!extension_loaded('gd')) {
214
			throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
215
		}
216
 
217
		if ($width < 1 || $height < 1) {
218
			throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.');
219
		}
220
 
221
		$image = imagecreatetruecolor($width, $height);
222
		if ($color) {
223
			$color += ['alpha' => 0];
224
			$color = imagecolorresolvealpha($image, $color['red'], $color['green'], $color['blue'], $color['alpha']);
225
			imagealphablending($image, false);
226
			imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $color);
227
			imagealphablending($image, true);
228
		}
229
 
230
		return new static($image);
231
	}
232
 
233
 
234
	/**
235
	 * Returns the type of image from file.
236
	 */
237
	public static function detectTypeFromFile(string $file, &$width = null, &$height = null): ?int
238
	{
239
		[$width, $height, $type] = @getimagesize($file); // @ - files smaller than 12 bytes causes read error
240
		return isset(self::Formats[$type]) ? $type : null;
241
	}
242
 
243
 
244
	/**
245
	 * Returns the type of image from string.
246
	 */
247
	public static function detectTypeFromString(string $s, &$width = null, &$height = null): ?int
248
	{
249
		[$width, $height, $type] = @getimagesizefromstring($s); // @ - strings smaller than 12 bytes causes read error
250
		return isset(self::Formats[$type]) ? $type : null;
251
	}
252
 
253
 
254
	/**
255
	 * Returns the file extension for the given `Image::XXX` constant.
256
	 */
257
	public static function typeToExtension(int $type): string
258
	{
259
		if (!isset(self::Formats[$type])) {
260
			throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
261
		}
262
 
263
		return self::Formats[$type];
264
	}
265
 
266
 
267
	/**
268
	 * Returns the `Image::XXX` constant for given file extension.
269
	 */
270
	public static function extensionToType(string $extension): int
271
	{
272
		$extensions = array_flip(self::Formats) + ['jpg' => self::JPEG];
273
		$extension = strtolower($extension);
274
		if (!isset($extensions[$extension])) {
275
			throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'.");
276
		}
277
 
278
		return $extensions[$extension];
279
	}
280
 
281
 
282
	/**
283
	 * Returns the mime type for the given `Image::XXX` constant.
284
	 */
285
	public static function typeToMimeType(int $type): string
286
	{
287
		return 'image/' . self::typeToExtension($type);
288
	}
289
 
290
 
291
	/**
292
	 * Wraps GD image.
293
	 * @param  resource|\GdImage  $image
294
	 */
295
	public function __construct($image)
296
	{
297
		$this->setImageResource($image);
298
		imagesavealpha($image, true);
299
	}
300
 
301
 
302
	/**
303
	 * Returns image width.
304
	 */
305
	public function getWidth(): int
306
	{
307
		return imagesx($this->image);
308
	}
309
 
310
 
311
	/**
312
	 * Returns image height.
313
	 */
314
	public function getHeight(): int
315
	{
316
		return imagesy($this->image);
317
	}
318
 
319
 
320
	/**
321
	 * Sets image resource.
322
	 * @param  resource|\GdImage  $image
323
	 * @return static
324
	 */
325
	protected function setImageResource($image)
326
	{
327
		if (!$image instanceof \GdImage && !(is_resource($image) && get_resource_type($image) === 'gd')) {
328
			throw new Nette\InvalidArgumentException('Image is not valid.');
329
		}
330
 
331
		$this->image = $image;
332
		return $this;
333
	}
334
 
335
 
336
	/**
337
	 * Returns image GD resource.
338
	 * @return resource|\GdImage
339
	 */
340
	public function getImageResource()
341
	{
342
		return $this->image;
343
	}
344
 
345
 
346
	/**
347
	 * Scales an image.
348
	 * @param  int|string|null  $width in pixels or percent
349
	 * @param  int|string|null  $height in pixels or percent
350
	 * @return static
351
	 */
352
	public function resize($width, $height, int $flags = self::FIT)
353
	{
354
		if ($flags & self::EXACT) {
355
			return $this->resize($width, $height, self::FILL)->crop('50%', '50%', $width, $height);
356
		}
357
 
358
		[$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $flags);
359
 
360
		if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize
361
			$newImage = static::fromBlank($newWidth, $newHeight, self::rgb(0, 0, 0, 127))->getImageResource();
362
			imagecopyresampled(
363
				$newImage,
364
				$this->image,
365
				0,
366
				0,
367
				0,
368
				0,
369
				$newWidth,
370
				$newHeight,
371
				$this->getWidth(),
372
				$this->getHeight()
373
			);
374
			$this->image = $newImage;
375
		}
376
 
377
		if ($width < 0 || $height < 0) {
378
			imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL);
379
		}
380
 
381
		return $this;
382
	}
383
 
384
 
385
	/**
386
	 * Calculates dimensions of resized image.
387
	 * @param  int|string|null  $newWidth in pixels or percent
388
	 * @param  int|string|null  $newHeight in pixels or percent
389
	 */
390
	public static function calculateSize(
391
		int $srcWidth,
392
		int $srcHeight,
393
		$newWidth,
394
		$newHeight,
395
		int $flags = self::FIT
396
	): array {
397
		if ($newWidth === null) {
398
		} elseif (self::isPercent($newWidth)) {
399
			$newWidth = (int) round($srcWidth / 100 * abs($newWidth));
400
			$percents = true;
401
		} else {
402
			$newWidth = abs($newWidth);
403
		}
404
 
405
		if ($newHeight === null) {
406
		} elseif (self::isPercent($newHeight)) {
407
			$newHeight = (int) round($srcHeight / 100 * abs($newHeight));
408
			$flags |= empty($percents) ? 0 : self::STRETCH;
409
		} else {
410
			$newHeight = abs($newHeight);
411
		}
412
 
413
		if ($flags & self::STRETCH) { // non-proportional
414
			if (!$newWidth || !$newHeight) {
415
				throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.');
416
			}
417
 
418
			if ($flags & self::SHRINK_ONLY) {
419
				$newWidth = (int) round($srcWidth * min(1, $newWidth / $srcWidth));
420
				$newHeight = (int) round($srcHeight * min(1, $newHeight / $srcHeight));
421
			}
422
		} else {  // proportional
423
			if (!$newWidth && !$newHeight) {
424
				throw new Nette\InvalidArgumentException('At least width or height must be specified.');
425
			}
426
 
427
			$scale = [];
428
			if ($newWidth > 0) { // fit width
429
				$scale[] = $newWidth / $srcWidth;
430
			}
431
 
432
			if ($newHeight > 0) { // fit height
433
				$scale[] = $newHeight / $srcHeight;
434
			}
435
 
436
			if ($flags & self::FILL) {
437
				$scale = [max($scale)];
438
			}
439
 
440
			if ($flags & self::SHRINK_ONLY) {
441
				$scale[] = 1;
442
			}
443
 
444
			$scale = min($scale);
445
			$newWidth = (int) round($srcWidth * $scale);
446
			$newHeight = (int) round($srcHeight * $scale);
447
		}
448
 
449
		return [max($newWidth, 1), max($newHeight, 1)];
450
	}
451
 
452
 
453
	/**
454
	 * Crops image.
455
	 * @param  int|string  $left in pixels or percent
456
	 * @param  int|string  $top in pixels or percent
457
	 * @param  int|string  $width in pixels or percent
458
	 * @param  int|string  $height in pixels or percent
459
	 * @return static
460
	 */
461
	public function crop($left, $top, $width, $height)
462
	{
463
		[$r['x'], $r['y'], $r['width'], $r['height']]
464
			= static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
465
		if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') {
466
			$this->image = imagecrop($this->image, $r);
467
			imagesavealpha($this->image, true);
468
		} else {
469
			$newImage = static::fromBlank($r['width'], $r['height'], self::RGB(0, 0, 0, 127))->getImageResource();
470
			imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']);
471
			$this->image = $newImage;
472
		}
473
 
474
		return $this;
475
	}
476
 
477
 
478
	/**
479
	 * Calculates dimensions of cutout in image.
480
	 * @param  int|string  $left in pixels or percent
481
	 * @param  int|string  $top in pixels or percent
482
	 * @param  int|string  $newWidth in pixels or percent
483
	 * @param  int|string  $newHeight in pixels or percent
484
	 */
485
	public static function calculateCutout(int $srcWidth, int $srcHeight, $left, $top, $newWidth, $newHeight): array
486
	{
487
		if (self::isPercent($newWidth)) {
488
			$newWidth = (int) round($srcWidth / 100 * $newWidth);
489
		}
490
 
491
		if (self::isPercent($newHeight)) {
492
			$newHeight = (int) round($srcHeight / 100 * $newHeight);
493
		}
494
 
495
		if (self::isPercent($left)) {
496
			$left = (int) round(($srcWidth - $newWidth) / 100 * $left);
497
		}
498
 
499
		if (self::isPercent($top)) {
500
			$top = (int) round(($srcHeight - $newHeight) / 100 * $top);
501
		}
502
 
503
		if ($left < 0) {
504
			$newWidth += $left;
505
			$left = 0;
506
		}
507
 
508
		if ($top < 0) {
509
			$newHeight += $top;
510
			$top = 0;
511
		}
512
 
513
		$newWidth = min($newWidth, $srcWidth - $left);
514
		$newHeight = min($newHeight, $srcHeight - $top);
515
		return [$left, $top, $newWidth, $newHeight];
516
	}
517
 
518
 
519
	/**
520
	 * Sharpens image a little bit.
521
	 * @return static
522
	 */
523
	public function sharpen()
524
	{
525
		imageconvolution($this->image, [ // my magic numbers ;)
526
			[-1, -1, -1],
527
			[-1, 24, -1],
528
			[-1, -1, -1],
529
		], 16, 0);
530
		return $this;
531
	}
532
 
533
 
534
	/**
535
	 * Puts another image into this image.
536
	 * @param  int|string  $left in pixels or percent
537
	 * @param  int|string  $top in pixels or percent
538
	 * @param  int  $opacity 0..100
539
	 * @return static
540
	 */
541
	public function place(self $image, $left = 0, $top = 0, int $opacity = 100)
542
	{
543
		$opacity = max(0, min(100, $opacity));
544
		if ($opacity === 0) {
545
			return $this;
546
		}
547
 
548
		$width = $image->getWidth();
549
		$height = $image->getHeight();
550
 
551
		if (self::isPercent($left)) {
552
			$left = (int) round(($this->getWidth() - $width) / 100 * $left);
553
		}
554
 
555
		if (self::isPercent($top)) {
556
			$top = (int) round(($this->getHeight() - $height) / 100 * $top);
557
		}
558
 
559
		$output = $input = $image->image;
560
		if ($opacity < 100) {
561
			$tbl = [];
562
			for ($i = 0; $i < 128; $i++) {
563
				$tbl[$i] = round(127 - (127 - $i) * $opacity / 100);
564
			}
565
 
566
			$output = imagecreatetruecolor($width, $height);
567
			imagealphablending($output, false);
568
			if (!$image->isTrueColor()) {
569
				$input = $output;
570
				imagefilledrectangle($output, 0, 0, $width, $height, imagecolorallocatealpha($output, 0, 0, 0, 127));
571
				imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height);
572
			}
573
 
574
			for ($x = 0; $x < $width; $x++) {
575
				for ($y = 0; $y < $height; $y++) {
576
					$c = \imagecolorat($input, $x, $y);
577
					$c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24);
578
					\imagesetpixel($output, $x, $y, $c);
579
				}
580
			}
581
 
582
			imagealphablending($output, true);
583
		}
584
 
585
		imagecopy(
586
			$this->image,
587
			$output,
588
			$left,
589
			$top,
590
			0,
591
			0,
592
			$width,
593
			$height
594
		);
595
		return $this;
596
	}
597
 
598
 
599
	/**
600
	 * 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).
601
	 * @throws ImageException
602
	 */
603
	public function save(string $file, ?int $quality = null, ?int $type = null): void
604
	{
605
		$type = $type ?? self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
606
		$this->output($type, $quality, $file);
607
	}
608
 
609
 
610
	/**
611
	 * 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).
612
	 */
613
	public function toString(int $type = self::JPEG, ?int $quality = null): string
614
	{
615
		return Helpers::capture(function () use ($type, $quality) {
616
			$this->output($type, $quality);
617
		});
618
	}
619
 
620
 
621
	/**
622
	 * Outputs image to string.
623
	 */
624
	public function __toString(): string
625
	{
626
		try {
627
			return $this->toString();
628
		} catch (\Throwable $e) {
629
			if (func_num_args() || PHP_VERSION_ID >= 70400) {
630
				throw $e;
631
			}
632
 
633
			trigger_error('Exception in ' . __METHOD__ . "(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}", E_USER_ERROR);
634
			return '';
635
		}
636
	}
637
 
638
 
639
	/**
640
	 * 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).
641
	 * @throws ImageException
642
	 */
643
	public function send(int $type = self::JPEG, ?int $quality = null): void
644
	{
645
		header('Content-Type: ' . self::typeToMimeType($type));
646
		$this->output($type, $quality);
647
	}
648
 
649
 
650
	/**
651
	 * Outputs image to browser or file.
652
	 * @throws ImageException
653
	 */
654
	private function output(int $type, ?int $quality, ?string $file = null): void
655
	{
656
		switch ($type) {
657
			case self::JPEG:
658
				$quality = $quality === null ? 85 : max(0, min(100, $quality));
659
				$success = @imagejpeg($this->image, $file, $quality); // @ is escalated to exception
660
				break;
661
 
662
			case self::PNG:
663
				$quality = $quality === null ? 9 : max(0, min(9, $quality));
664
				$success = @imagepng($this->image, $file, $quality); // @ is escalated to exception
665
				break;
666
 
667
			case self::GIF:
668
				$success = @imagegif($this->image, $file); // @ is escalated to exception
669
				break;
670
 
671
			case self::WEBP:
672
				$quality = $quality === null ? 80 : max(0, min(100, $quality));
673
				$success = @imagewebp($this->image, $file, $quality); // @ is escalated to exception
674
				break;
675
 
676
			case self::AVIF:
677
				$quality = $quality === null ? 30 : max(0, min(100, $quality));
678
				$success = @imageavif($this->image, $file, $quality); // @ is escalated to exception
679
				break;
680
 
681
			case self::BMP:
682
				$success = @imagebmp($this->image, $file); // @ is escalated to exception
683
				break;
684
 
685
			default:
686
				throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
687
		}
688
 
689
		if (!$success) {
690
			throw new ImageException(Helpers::getLastError() ?: 'Unknown error');
691
		}
692
	}
693
 
694
 
695
	/**
696
	 * Call to undefined method.
697
	 * @return mixed
698
	 * @throws Nette\MemberAccessException
699
	 */
700
	public function __call(string $name, array $args)
701
	{
702
		$function = 'image' . $name;
703
		if (!function_exists($function)) {
704
			ObjectHelpers::strictCall(static::class, $name);
705
		}
706
 
707
		foreach ($args as $key => $value) {
708
			if ($value instanceof self) {
709
				$args[$key] = $value->getImageResource();
710
 
711
			} elseif (is_array($value) && isset($value['red'])) { // rgb
712
				$args[$key] = imagecolorallocatealpha(
713
					$this->image,
714
					$value['red'],
715
					$value['green'],
716
					$value['blue'],
717
					$value['alpha']
718
				) ?: imagecolorresolvealpha(
719
					$this->image,
720
					$value['red'],
721
					$value['green'],
722
					$value['blue'],
723
					$value['alpha']
724
				);
725
			}
726
		}
727
 
728
		$res = $function($this->image, ...$args);
729
		return $res instanceof \GdImage || (is_resource($res) && get_resource_type($res) === 'gd')
730
			? $this->setImageResource($res)
731
			: $res;
732
	}
733
 
734
 
735
	public function __clone()
736
	{
737
		ob_start(function () {});
738
		imagepng($this->image, null, 0);
739
		$this->setImageResource(imagecreatefromstring(ob_get_clean()));
740
	}
741
 
742
 
743
	/**
744
	 * @param  int|string  $num in pixels or percent
745
	 */
746
	private static function isPercent(&$num): bool
747
	{
748
		if (is_string($num) && substr($num, -1) === '%') {
749
			$num = (float) substr($num, 0, -1);
750
			return true;
751
		} elseif (is_int($num) || $num === (string) (int) $num) {
752
			$num = (int) $num;
753
			return false;
754
		}
755
 
756
		throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given.");
757
	}
758
 
759
 
760
	/**
761
	 * Prevents serialization.
762
	 */
763
	public function __sleep(): array
764
	{
765
		throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.');
766
	}
767
}