forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseHandler.php
More file actions
783 lines (674 loc) · 19.9 KB
/
BaseHandler.php
File metadata and controls
783 lines (674 loc) · 19.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Images\Handlers;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Images\Exceptions\ImageException;
use CodeIgniter\Images\Image;
use CodeIgniter\Images\ImageHandlerInterface;
use Config\Images;
/**
* Base image handling implementation
*/
abstract class BaseHandler implements ImageHandlerInterface
{
/**
* Configuration settings.
*
* @var Images
*/
protected $config;
/**
* The image/file instance
*
* @var Image|null
*/
protected $image;
/**
* Whether the image file has been confirmed.
*
* @var bool
*/
protected $verified = false;
/**
* Image width.
*
* @var int
*/
protected $width = 0;
/**
* Image height.
*
* @var int
*/
protected $height = 0;
/**
* File permission mask.
*
* @var int
*/
protected $filePermissions = 0644;
/**
* X-axis.
*
* @var int|null
*/
protected $xAxis = 0;
/**
* Y-axis.
*
* @var int|null
*/
protected $yAxis = 0;
/**
* Master dimensioning.
*
* @var string
*/
protected $masterDim = 'auto';
/**
* Default options for text watermarking.
*
* @var array
*/
protected $textDefaults = [
'fontPath' => null,
'fontSize' => 16,
'color' => 'ffffff',
'opacity' => 1.0,
'vAlign' => 'bottom',
'hAlign' => 'center',
'vOffset' => 0,
'hOffset' => 0,
'padding' => 0,
'withShadow' => false,
'shadowColor' => '000000',
'shadowOffset' => 3,
];
/**
* Image types with support for transparency.
*
* @var array
*/
protected $supportTransparency = [
IMAGETYPE_PNG,
IMAGETYPE_WEBP,
IMAGETYPE_AVIF,
];
/**
* Temporary image used by the different engines.
*
* @var resource|null
*/
protected $resource;
/**
* Constructor.
*
* @param Images|null $config
*/
public function __construct($config = null)
{
$this->config = $config ?? new Images();
}
/**
* Sets another image for this handler to work on.
* Keeps us from needing to continually instantiate the handler.
*
* @phpstan-assert Image $this->image
*
* @return $this
*/
public function withFile(string $path)
{
// Clear out the old resource so that
// it doesn't try to use a previous image
$this->resource = null;
$this->verified = false;
$this->image = new Image($path, true);
$this->image->getProperties(false);
$this->width = $this->image->origWidth;
$this->height = $this->image->origHeight;
return $this;
}
/**
* Make the image resource object if needed
*
* @return void
*/
abstract protected function ensureResource();
/**
* Returns the image instance.
*
* @return Image
*/
public function getFile()
{
return $this->image;
}
/**
* Verifies that a file has been supplied and it is an image.
*
* @phpstan-assert Image $this->image
*
* @throws ImageException
*/
protected function image(): Image
{
if ($this->verified) {
return $this->image;
}
// Verify withFile has been called
if ($this->image === null) {
throw ImageException::forMissingImage();
}
// Verify the loaded image is an Image instance
if (! $this->image instanceof Image) {
throw ImageException::forInvalidPath();
}
// File::__construct has verified the file exists - make sure it is an image
if (! is_int($this->image->imageType)) {
throw ImageException::forFileNotSupported();
}
// Note that the image has been verified
$this->verified = true;
return $this->image;
}
/**
* Returns the temporary image used during the image processing.
* Good for extending the system or doing things this library
* is not intended to do.
*
* @return resource
*/
public function getResource()
{
$this->ensureResource();
return $this->resource;
}
/**
* Load the temporary image used during the image processing.
* Some functions e.g. save() will only copy and not compress
* your image otherwise.
*
* @return $this
*/
public function withResource()
{
$this->ensureResource();
return $this;
}
/**
* Resize the image
*
* @param bool $maintainRatio If true, will get the closest match possible while keeping aspect ratio true.
*
* @return BaseHandler
*/
public function resize(int $width, int $height, bool $maintainRatio = false, string $masterDim = 'auto')
{
// If the target width/height match the source, then we have nothing to do here.
if ($this->image()->origWidth === $width && $this->image()->origHeight === $height) {
return $this;
}
$this->width = $width;
$this->height = $height;
if ($maintainRatio) {
$this->masterDim = $masterDim;
$this->reproportion();
}
return $this->_resize($maintainRatio);
}
/**
* Crops the image to the desired height and width. If one of the height/width values
* is not provided, that value will be set the appropriate value based on offsets and
* image dimensions.
*
* @param int|null $x X-axis coord to start cropping from the left of image
* @param int|null $y Y-axis coord to start cropping from the top of image
*
* @return $this
*/
public function crop(?int $width = null, ?int $height = null, ?int $x = null, ?int $y = null, bool $maintainRatio = false, string $masterDim = 'auto')
{
$this->width = $width;
$this->height = $height;
$this->xAxis = $x;
$this->yAxis = $y;
if ($maintainRatio) {
$this->masterDim = $masterDim;
$this->reproportion();
}
$result = $this->_crop();
$this->xAxis = null;
$this->yAxis = null;
return $result;
}
/**
* Changes the stored image type to indicate the new file format to use when saving.
* Does not touch the actual resource.
*
* @param int $imageType A PHP imageType constant, e.g. https://www.php.net/manual/en/function.image-type-to-mime-type.php
*
* @return $this
*/
public function convert(int $imageType)
{
$this->ensureResource();
$this->image()->imageType = $imageType;
return $this;
}
/**
* Rotates the image on the current canvas.
*
* @return $this
*/
public function rotate(float $angle)
{
// Allowed rotation values
$degs = [
90.0,
180.0,
270.0,
];
if (! in_array($angle, $degs, true)) {
throw ImageException::forMissingAngle();
}
// cast angle as an int, for our use
$angle = (int) $angle;
// Reassign the width and height
if ($angle === 90 || $angle === 270) {
$temp = $this->height;
$this->width = $this->height;
$this->height = $temp;
}
// Call the Handler-specific version.
$this->_rotate($angle);
return $this;
}
/**
* Flattens transparencies, default white background
*
* @return $this
*/
public function flatten(int $red = 255, int $green = 255, int $blue = 255)
{
$this->width = $this->image()->origWidth;
$this->height = $this->image()->origHeight;
return $this->_flatten($red, $green, $blue);
}
/**
* Handler-specific method to flattening an image's transparencies.
*
* @return $this
*
* @internal
*/
abstract protected function _flatten(int $red = 255, int $green = 255, int $blue = 255);
/**
* Handler-specific method to handle rotating an image in 90 degree increments.
*
* @return mixed
*/
abstract protected function _rotate(int $angle);
/**
* Flips an image either horizontally or vertically.
*
* @param string $dir Either 'vertical' or 'horizontal'
*
* @return $this
*/
public function flip(string $dir = 'vertical')
{
$dir = strtolower($dir);
if ($dir !== 'vertical' && $dir !== 'horizontal') {
throw ImageException::forInvalidDirection($dir);
}
return $this->_flip($dir);
}
/**
* Handler-specific method to handle flipping an image along its
* horizontal or vertical axis.
*
* @return $this
*/
abstract protected function _flip(string $direction);
public function text(string $text, array $options = [])
{
$options = array_merge($this->textDefaults, $options);
$options['color'] = trim($options['color'], '# ');
$options['shadowColor'] = trim($options['shadowColor'], '# ');
$this->_text($text, $options);
return $this;
}
/**
* Handler-specific method for overlaying text on an image.
*
* @param array{
* color?: string,
* shadowColor?: string,
* hAlign?: string,
* vAlign?: string,
* hOffset?: int,
* vOffset?: int,
* fontPath?: string,
* fontSize?: int,
* shadowOffset?: int,
* opacity?: float,
* padding?: int,
* withShadow?: bool|string
* } $options
*
* @return void
*/
abstract protected function _text(string $text, array $options = []);
/**
* Handles the actual resizing of the image.
*
* @return $this
*/
abstract public function _resize(bool $maintainRatio = false);
/**
* Crops the image.
*
* @return $this
*/
abstract public function _crop();
/**
* Return image width.
*
* @return int
*/
abstract public function _getWidth();
/**
* Return the height of an image.
*
* @return int
*/
abstract public function _getHeight();
/**
* Reads the EXIF information from the image and modifies the orientation
* so that displays correctly in the browser. This is especially an issue
* with images taken by smartphones who always store the image up-right,
* but set the orientation flag to display it correctly.
*
* @param bool $silent If true, will ignore exceptions when PHP doesn't support EXIF.
*
* @return $this
*/
public function reorient(bool $silent = false)
{
$orientation = $this->getEXIF('Orientation', $silent);
return match ($orientation) {
2 => $this->flip('horizontal'),
3 => $this->rotate(180),
4 => $this->rotate(180)->flip('horizontal'),
5 => $this->rotate(270)->flip('horizontal'),
6 => $this->rotate(270),
7 => $this->rotate(90)->flip('horizontal'),
8 => $this->rotate(90),
default => $this,
};
}
/**
* Retrieve the EXIF information from the image, if possible. Returns
* an array of the information, or null if nothing can be found.
*
* EXIF data is only supported fr JPEG & TIFF formats.
*
* @param string|null $key If specified, will only return this piece of EXIF data.
* @param bool $silent If true, will not throw our own exceptions.
*
* @return mixed
*
* @throws ImageException
*/
public function getEXIF(?string $key = null, bool $silent = false)
{
if (! function_exists('exif_read_data')) {
if ($silent) {
return null;
}
throw ImageException::forEXIFUnsupported(); // @codeCoverageIgnore
}
$exif = null; // default
switch ($this->image()->imageType) {
case IMAGETYPE_JPEG:
case IMAGETYPE_TIFF_II:
$exif = @exif_read_data($this->image()->getPathname());
if ($key !== null && is_array($exif)) {
$exif = $exif[$key] ?? false;
}
}
return $exif;
}
/**
* Combine cropping and resizing into a single command.
*
* Supported positions:
* - top-left
* - top
* - top-right
* - left
* - center
* - right
* - bottom-left
* - bottom
* - bottom-right
*
* @return BaseHandler
*/
public function fit(int $width, ?int $height = null, string $position = 'center')
{
$origWidth = $this->image()->origWidth;
$origHeight = $this->image()->origHeight;
[$cropWidth, $cropHeight] = $this->calcAspectRatio($width, $height, $origWidth, $origHeight);
if ($height === null) {
$height = (int) ceil(($width / $cropWidth) * $cropHeight);
}
[$x, $y] = $this->calcCropCoords($cropWidth, $cropHeight, $origWidth, $origHeight, $position);
return $this->crop($cropWidth, $cropHeight, (int) $x, (int) $y)->resize($width, $height);
}
/**
* Calculate image aspect ratio.
*
* @param float|int $width
* @param float|int|null $height
* @param float|int $origWidth
* @param float|int $origHeight
*/
protected function calcAspectRatio($width, $height = null, $origWidth = 0, $origHeight = 0): array
{
if (empty($origWidth) || empty($origHeight)) {
throw new InvalidArgumentException('You must supply the parameters: origWidth, origHeight.');
}
// If $height is null, then we have it easy.
// Calc based on full image size and be done.
if ($height === null) {
$height = ($width / $origWidth) * $origHeight;
return [
$width,
(int) $height,
];
}
$xRatio = $width / $origWidth;
$yRatio = $height / $origHeight;
if ($xRatio > $yRatio) {
return [
$origWidth,
(int) ($origWidth * $height / $width),
];
}
return [
(int) ($origHeight * $width / $height),
$origHeight,
];
}
/**
* Based on the position, will determine the correct x/y coords to
* crop the desired portion from the image.
*
* @param float|int $width
* @param float|int $height
* @param float|int $origWidth
* @param float|int $origHeight
* @param string $position
*/
protected function calcCropCoords($width, $height, $origWidth, $origHeight, $position): array
{
$position = strtolower($position);
$x = $y = 0;
switch ($position) {
case 'top-left':
$x = 0;
$y = 0;
break;
case 'top':
$x = floor(($origWidth - $width) / 2);
$y = 0;
break;
case 'top-right':
$x = $origWidth - $width;
$y = 0;
break;
case 'left':
$x = 0;
$y = floor(($origHeight - $height) / 2);
break;
case 'center':
$x = floor(($origWidth - $width) / 2);
$y = floor(($origHeight - $height) / 2);
break;
case 'right':
$x = ($origWidth - $width);
$y = floor(($origHeight - $height) / 2);
break;
case 'bottom-left':
$x = 0;
$y = $origHeight - $height;
break;
case 'bottom':
$x = floor(($origWidth - $width) / 2);
$y = $origHeight - $height;
break;
case 'bottom-right':
$x = ($origWidth - $width);
$y = $origHeight - $height;
break;
}
return [
$x,
$y,
];
}
/**
* Get the version of the image library in use.
*
* @return string
*/
abstract public function getVersion();
/**
* Saves any changes that have been made to file.
*
* Example:
* $image->resize(100, 200, true)
* ->save($target);
*
* @param non-empty-string|null $target
*
* @return bool
*/
abstract public function save(?string $target = null, int $quality = 90, int $speed = -1);
/**
* Does the driver-specific processing of the image.
*
* @return mixed
*/
abstract protected function process(string $action);
/**
* Provide access to the Image class' methods if they don't exist
* on the handler itself.
*
* @return mixed
*/
public function __call(string $name, array $args = [])
{
if (method_exists($this->image(), $name)) {
return $this->image()->{$name}(...$args);
}
return null;
}
/**
* Re-proportion Image Width/Height
*
* When creating thumbs, the desired width/height
* can end up warping the image due to an incorrect
* ratio between the full-sized image and the thumb.
*
* This function lets us re-proportion the width/height
* if users choose to maintain the aspect ratio when resizing.
*
* @return void
*/
protected function reproportion()
{
if (($this->width === 0 && $this->height === 0) || $this->image()->origWidth === 0 || $this->image()->origHeight === 0 || (! ctype_digit((string) $this->width) && ! ctype_digit((string) $this->height)) || ! ctype_digit((string) $this->image()->origWidth) || ! ctype_digit((string) $this->image()->origHeight)) {
return;
}
// Sanitize
$this->width = (int) $this->width;
$this->height = (int) $this->height;
if ($this->masterDim !== 'width' && $this->masterDim !== 'height') {
if ($this->width > 0 && $this->height > 0) {
$this->masterDim = ((($this->image()->origHeight / $this->image()->origWidth) - ($this->height / $this->width)) < 0) ? 'width' : 'height';
} else {
$this->masterDim = ($this->height === 0) ? 'width' : 'height';
}
} elseif (($this->masterDim === 'width' && $this->width === 0) || ($this->masterDim === 'height' && $this->height === 0)
) {
return;
}
if ($this->masterDim === 'width') {
$this->height = (int) ceil($this->width * $this->image()->origHeight / $this->image()->origWidth);
} else {
$this->width = (int) ceil($this->image()->origWidth * $this->height / $this->image()->origHeight);
}
}
/**
* Return image width.
*
* accessor for testing; not part of interface
*
* @return int
*/
public function getWidth()
{
return ($this->resource !== null) ? $this->_getWidth() : $this->width;
}
/**
* Return image height.
*
* accessor for testing; not part of interface
*
* @return int
*/
public function getHeight()
{
return ($this->resource !== null) ? $this->_getHeight() : $this->height;
}
/**
* Placeholder method for implementing metadata clearing logic.
*
* This method should be implemented to remove or reset metadata as needed.
*/
public function clearMetadata(): static
{
return $this;
}
}