Subversion-Projekte lars-tiefland.laravel_shop

Revision

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