forked from Gregwar/Image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Image.php
987 lines (857 loc) · 22.5 KB
/
Image.php
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
<?php
namespace Gregwar\Image;
use Gregwar\Cache\Cache;
use Gregwar\Cache\CacheInterface;
use Gregwar\Image\Adapter\AdapterInterface;
use Gregwar\Image\Adapter\GD;
use Gregwar\Image\Adapter\Imagick;
use Gregwar\Image\Exceptions\GenerationError;
use Gregwar\Image\Source\Create;
use Gregwar\Image\Source\Data;
use Gregwar\Image\Source\File;
use Gregwar\Image\Source\Resource;
use Gregwar\Image\Source\Source;
/**
* Images handling class.
*
* @author Gregwar <[email protected]>
*
* @method Image saveGif($file)
* @method Image savePng($file)
* @method Image saveJpeg($file, $quality)
* @method Image saveWebP($file, $quality)
* @method Image saveAvif($file, $quality)
* @method Image resize($width = null, $height = null, $background = 'transparent', $force = false, $rescale = false, $crop = false)
* @method Image forceResize($width = null, $height = null, $background = 'transparent')
* @method Image scaleResize($width = null, $height = null, $background = 'transparent', $crop = false)
* @method Image cropResize($width = null, $height = null, $background=0xffffff)
* @method Image scale($width = null, $height = null, $background=0xffffff, $crop = false)
* @method Image ($width = null, $height = null, $background = 0xffffff, $force = false, $rescale = false, $crop = false)
* @method Image crop($x, $y, $width, $height)
* @method Image enableProgressive()
* @method Image force($width = null, $height = null, $background = 0xffffff)
* @method Image zoomCrop($width, $height, $background = 'transparent', $xPosLetter = 'center', $yPosLetter = 'center')
* @method Image fillBackground($background = 0xffffff)
* @method Image negate()
* @method Image brightness($brightness)
* @method Image contrast($contrast)
* @method Image grayscale()
* @method Image emboss()
* @method Image smooth($p)
* @method Image sharp()
* @method Image edge()
* @method Image colorize($red, $green, $blue)
* @method Image sepia()
* @method Image merge(Image $other, $x = 0, $y = 0, $width = null, $height = null)
* @method Image rotate($angle, $background = 0xffffff)
* @method Image fill($color = 0xffffff, $x = 0, $y = 0)
* @method Image write($font, $text, $x = 0, $y = 0, $size = 12, $angle = 0, $color = 0x000000, $align = 'left')
* @method Image rectangle($x1, $y1, $x2, $y2, $color, $filled = false)
* @method Image roundedRectangle($x1, $y1, $x2, $y2, $radius, $color, $filled = false)
* @method Image line($x1, $y1, $x2, $y2, $color = 0x000000)
* @method Image ellipse($cx, $cy, $width, $height, $color = 0x000000, $filled = false)
* @method Image circle($cx, $cy, $r, $color = 0x000000, $filled = false)
* @method Image polygon(array $points, $color, $filled = false)
* @method Image flip($flipVertical, $flipHorizontal)
*/
class Image
{
/**
* Directory to use for file caching.
* @var string
*/
protected $cacheDir = 'cache/images';
/**
* Directory cache mode. Not used.
* @var null
*/
protected $cacheMode;
/**
* Internal adapter.
*
* @var AdapterInterface|null
*/
protected $adapter;
/**
* Pretty name for the image.
* @var string
*/
protected $prettyName = '';
/** @var bool */
protected $prettyPrefix = false;
/**
* Transformations hash.
* @var string|null
*/
protected $hash;
/**
* The image source.
* @var Source|null
*/
protected $source;
/**
* Force image caching, even if there is no operation applied.
* @var bool
*/
protected $forceCache = true;
/**
* Supported types.
* @var array
*/
public static $types = array(
'jpg' => 'jpeg',
'jpeg' => 'jpeg',
'webp' => 'webp',
'avif' => 'avif',
'png' => 'png',
'gif' => 'gif',
);
/**
* Fallback image.
* @var string
*/
protected $fallback;
/**
* Use fallback image.
* @var bool
*/
protected $useFallbackImage = true;
/**
* Cache system.
*
* @var CacheInterface
*/
protected $cache;
/**
* Get the cache system.
*
* @return CacheInterface
*/
public function getCacheSystem()
{
if (is_null($this->cache)) {
$this->cache = new Cache();
$this->cache->setCacheDirectory($this->cacheDir);
}
return $this->cache;
}
/**
* Set the cache system.
*
* @param CacheInterface $cache
*
* @return void
*/
public function setCacheSystem(CacheInterface $cache)
{
$this->cache = $cache;
}
/**
* Change the caching directory.
*
* @param string $cacheDir
*
* @return $this
*/
public function setCacheDir($cacheDir)
{
$this->getCacheSystem()->setCacheDirectory($cacheDir);
return $this;
}
/**
* @param int $dirMode
*
* @return void
*/
public function setCacheDirMode($dirMode)
{
$this->cache->setDirectoryMode($dirMode);
}
/**
* Enable or disable to force cache even if the file is unchanged.
*
* @param bool $forceCache
*
* @return $this
*/
public function setForceCache($forceCache = true)
{
$this->forceCache = $forceCache;
return $this;
}
/**
* The actual cache dir.
*
* @param string|null $actualCacheDir
*
* @return $this
*/
public function setActualCacheDir($actualCacheDir)
{
$this->getCacheSystem()->setActualCacheDirectory($actualCacheDir);
return $this;
}
/**
* Sets the pretty name of the image.
*
* @param string $name
* @param bool $prefix
*/
public function setPrettyName($name, $prefix = true)
{
if (empty($name)) {
return $this;
}
$this->prettyName = $this->urlize($name);
$this->prettyPrefix = $prefix;
return $this;
}
/**
* Urlizes the prettyName.
*
* @param string $name
*
* @return string
*/
protected function urlize($name)
{
$transliterator = '\Behat\Transliterator\Transliterator';
if (class_exists($transliterator)) {
$name = $transliterator::transliterate($name);
$name = $transliterator::urlize($name);
} else {
$name = strtolower($name);
$name = str_replace(' ', '-', $name);
$name = preg_replace('/([^a-z0-9\-]+)/m', '', $name);
}
return $name;
}
/**
* Operations array.
* @var array
*/
protected $operations = array();
/**
* Image constructor.
*
* @param string|null $originalFile
* @param int|null $width
* @param int|null $height
*/
public function __construct($originalFile = null, $width = null, $height = null)
{
$this->setFallback(null);
if ($originalFile) {
$this->source = new File($originalFile);
} else {
$this->source = new Create($width, $height);
}
}
/**
* Sets the image data.
*
* @param string $data
*
* @return void
*/
public function setData($data)
{
$this->source = new Data($data);
}
/**
* Sets the resource.
*
* @param resource $resource
*
* @return void
*/
public function setResource($resource)
{
$this->source = new Resource($resource);
}
/**
* Use the fallback image or not.
*
* @param bool $useFallbackImage
*
* @return $this
*/
public function useFallback($useFallbackImage = true)
{
$this->useFallbackImage = $useFallbackImage;
return $this;
}
/**
* Sets the fallback image to use.
*
* @param string|null $fallback
*
* @return $this
*/
public function setFallback($fallback = null)
{
if ($fallback === null) {
$this->fallback = __DIR__.'/images/error.jpg';
} else {
$this->fallback = $fallback;
}
return $this;
}
/**
* Gets the fallback image path.
*
* @return string
*/
public function getFallback()
{
return $this->fallback;
}
/**
* Gets the fallback into the cache dir.
*
* @return string
*/
public function getCacheFallback()
{
$fallback = $this->fallback;
return $this->getCacheSystem()->getOrCreateFile('fallback.jpg', array(), function ($target) use ($fallback) {
copy($fallback, $target);
});
}
/**
* @return AdapterInterface
*/
public function getAdapter()
{
if (null === $this->adapter) {
// Defaults to GD
$this->setAdapter('gd');
}
return $this->adapter;
}
/**
* @param AdapterInterface|string $adapter
* @throws \Exception
*/
public function setAdapter($adapter)
{
if ($adapter instanceof AdapterInterface) {
$this->adapter = $adapter;
} else {
if (is_string($adapter)) {
$adapter = strtolower($adapter);
switch ($adapter) {
case 'gd':
$this->adapter = new GD();
break;
case 'imagemagick':
case 'imagick':
$this->adapter = new Imagick();
break;
default:
throw new \Exception('Unknown adapter: ' . $adapter);
}
} else {
throw new \Exception('Unable to load the given adapter (not string or Adapter)');
}
}
$this->adapter->setSource($this->source);
}
/**
* Get the file path.
*
* @return string|null a string with the filename, null if the image does not depends on a file
* does not depend on a file
*/
public function getFilePath()
{
if ($this->source instanceof File) {
return $this->source->getFile();
}
return null;
}
/**
* Defines the file only after instantiation.
*
* @param string $originalFile the file path
*
* @return $this
*/
public function fromFile($originalFile)
{
$this->source = new File($originalFile);
return $this;
}
/**
* Tells if the image is correct.
*
* @return bool
*/
public function correct()
{
return $this->source->correct();
}
/**
* Guess the file type.
*
* @return string
*/
public function guessType()
{
return $this->source->guessType();
}
/**
* Adds an operation.
*
* @param string $method
* @param mixed $args
*
* @return void
*/
protected function addOperation($method, $args)
{
$this->operations[] = array($method, $args);
}
/**
* Generic function.
*
* @param string $methodName
* @param array $args
*
* @return $this
*/
public function __call($methodName, $args)
{
$adapter = $this->getAdapter();
$reflection = new \ReflectionClass(get_class($adapter));
if ($reflection->hasMethod($methodName)) {
$method = $reflection->getMethod($methodName);
if ($method->getNumberOfRequiredParameters() > count($args)) {
throw new \InvalidArgumentException('Not enough arguments given for '.$methodName);
}
$this->addOperation($methodName, $args);
return $this;
}
throw new \BadFunctionCallException('Invalid method: '.$methodName);
}
/**
* Serialization of operations.
*
* @return string
*/
public function serializeOperations()
{
$datas = array();
foreach ($this->operations as $operation) {
$method = $operation[0];
$args = $operation[1];
foreach ($args as &$arg) {
if ($arg instanceof self) {
$arg = $arg->getHash();
}
}
unset($arg);
$datas[] = array($method, $args);
}
return serialize($datas);
}
/**
* Generates the hash.
*
* @param string $type
* @param int $quality
*
* @return void
*/
public function generateHash($type = 'guess', $quality = 80)
{
$inputRelativePath = substr($this->source->getInfos(), strlen(getcwd()) + 1);
$datas = array(
$inputRelativePath,
$this->serializeOperations(),
$type,
$quality,
);
$this->hash = sha1(serialize($datas));
}
/**
* Gets the hash.
*
* @param string $type
* @param int $quality
*
* @return string
*/
public function getHash($type = 'guess', $quality = 80)
{
if (null === $this->hash) {
$this->generateHash($type, $quality);
}
return $this->hash;
}
/**
* Gets the cache file name and generate it if it does not exist.
* Note that if it exists, all the image computation process will
* not be done.
*
* @param string $type the image type
* @param int $quality the quality (for JPEG)
* @param bool $actual
*
* @return string
*/
public function cacheFile($type = 'jpg', $quality = 80, $actual = false)
{
if ($type === 'guess') {
$type = $this->guessType();
}
if (!count($this->operations) && $type === $this->guessType() && !$this->forceCache) {
return $this->getFilename($this->getFilePath());
}
// Computes the hash
$this->hash = $this->getHash($type, $quality);
// Generates the cache file
$cacheFile = '';
if (!$this->prettyName || $this->prettyPrefix) {
$cacheFile .= $this->hash;
}
if ($this->prettyPrefix) {
$cacheFile .= '-';
}
if ($this->prettyName) {
$cacheFile .= $this->prettyName;
}
$cacheFile .= '.'.$type;
// If the file does not exist, save it
$image = $this;
// Target file should be younger than all the current image
// dependencies
$conditions = array(
'younger-than' => $this->getDependencies(),
);
// The generating function
$generate = function ($target) use ($image, $type, $quality) {
$result = $image->save($target, $type, $quality);
if ($result != $target) {
throw new GenerationError($result);
}
};
// Asking the cache for the cacheFile
try {
$file = $this->getCacheSystem()->getOrCreateFile($cacheFile, $conditions, $generate, $actual);
} catch (GenerationError $e) {
$file = $e->getNewFile();
}
// Nulling the resource
$this->getAdapter()->setSource(new File($file));
$this->getAdapter()->deinit();
if ($actual) {
return $file;
}
return $this->getFilename($file);
}
/**
* Get cache data (to render the image).
*
* @param string $type the image type
* @param int $quality the quality (for JPEG)
*
* @return string|false
*/
public function cacheData($type = 'jpg', $quality = 80)
{
return file_get_contents($this->cacheFile($type, $quality));
}
/**
* Hook to helps to extends and enhance this class.
*
* @param string $filename
*
* @return string
*/
protected function getFilename($filename)
{
return $filename;
}
/**
* Generates and output a jpeg cached file.
*
* @param int $quality
*
* @return string
*/
public function jpeg($quality = 80)
{
return $this->cacheFile('jpg', $quality);
}
/**
* Generates and output a gif cached file.
*
* @return string
*/
public function gif()
{
return $this->cacheFile('gif');
}
/**
* Generates and output a png cached file.
*
* @return string
*/
public function png()
{
return $this->cacheFile('png');
}
/**
* Generates and output a webp cached file.
*
* @param int $quality
*
* @return string
*/
public function webp($quality = 80)
{
return $this->cacheFile('webp', $quality);
}
/**
* Generates and output a webp cached file.
*/
public function avif($quality = 80)
{
return $this->cacheFile('avif', $quality);
}
/**
* Generates and output an image using the same type as input.
*
* @param int $quality
*
* @return string
*/
public function guess($quality = 80)
{
return $this->cacheFile('guess', $quality);
}
/**
* Get all the files that this image depends on.
*
* @return string[] this is an array of strings containing all the files that the
* current Image depends on
*/
public function getDependencies()
{
$dependencies = array();
$file = $this->getFilePath();
if ($file) {
$dependencies[] = $file;
}
foreach ($this->operations as $operation) {
foreach ($operation[1] as $argument) {
if ($argument instanceof self) {
$dependencies = array_merge($dependencies, $argument->getDependencies());
}
}
}
return $dependencies;
}
/**
* Applies the operations.
*
* @return void
*/
public function applyOperations()
{
// Renders the effects
foreach ($this->operations as $operation) {
call_user_func_array(array($this->adapter, $operation[0]), $operation[1]);
}
}
/**
* Initialize the adapter.
*
* @return void
*/
public function init()
{
$this->getAdapter()->init();
}
/**
* Save the file to a given output.
*
* @param string $file
* @param string|int $type
* @param int $quality
* @return string|false
* @throws \Exception
*/
public function save($file, $type = 'guess', $quality = 80)
{
if ($file) {
$directory = dirname($file);
if (!is_dir($directory)) {
@mkdir($directory, 0777, true);
}
}
if (is_int($type)) {
$quality = $type;
$type = 'jpeg';
}
if ($type === 'guess') {
$type = $this->guessType();
}
if (!isset(self::$types[$type])) {
throw new \InvalidArgumentException('Given type ('.$type.') is not valid');
}
$type = self::$types[$type];
try {
$this->init();
$this->applyOperations();
$success = false;
if (null === $file) {
ob_start();
}
if ($type === 'jpeg') {
$success = $this->getAdapter()->saveJpeg($file, $quality);
}
if ($type === 'gif') {
$success = $this->getAdapter()->saveGif($file);
}
if ($type === 'png') {
$success = $this->getAdapter()->savePng($file);
}
if ($type === 'webp') {
$success = $this->getAdapter()->saveWebP($file, $quality);
}
if ($type == 'avif') {
$success = $this->getAdapter()->saveAvif($file, $quality);
}
if (!$success) {
return false;
}
return null === $file ? ob_get_clean() : $file;
} catch (\Exception $e) {
if ($this->useFallbackImage) {
return null === $file ? file_get_contents($this->fallback) : $this->getCacheFallback();
} else {
throw $e;
}
}
}
/**
* Get the contents of the image.
*
* @param string|int $type
* @param int $quality
* @return string|false
* @throws \Exception
*/
public function get($type = 'guess', $quality = 80)
{
return $this->save(null, $type, $quality);
}
/* Image API */
/**
* Image width.
*
* @return int
*/
public function width()
{
return $this->getAdapter()->width();
}
/**
* Image height.
*
* @return int
*/
public function height()
{
return $this->getAdapter()->height();
}
/**
* Tostring defaults to jpeg.
*
* @return string
*/
public function __toString()
{
return $this->guess();
}
/**
* Returning basic html code for this image.
*
* @param string $title
* @param string $type
* @param int $quality
*
* @return string
*/
public function html($title = '', $type = 'jpg', $quality = 80)
{
return '<img title="'.$title.'" src="'.$this->cacheFile($type, $quality).'" />';
}
/**
* Returns the Base64 inlineable representation.
*
* @param string $type
* @param int $quality
*
* @return string
*/
public function inline($type = 'jpg', $quality = 80)
{
$mime = $type;
if ($mime === 'jpg') {
$mime = 'jpeg';
}
return 'data:image/'.$mime.';base64,'.base64_encode(file_get_contents($this->cacheFile($type, $quality, true)));
}
/**
* Creates an instance, useful for one-line chaining.
*
* @param string $file
*
* @return static
*/
public static function open($file = '')
{
return new static($file);
}
/**
* Creates an instance of a new resource.
*
* @param int $width
* @param int $height
*
* @return static
*/
public static function create($width, $height)
{
return new static(null, $width, $height);
}
/**
* Creates an instance of image from its data.
*
* @param string $data
*
* @return static
*/
public static function fromData($data)
{
$image = new static();
$image->setData($data);
return $image;
}
/**
* Creates an instance of image from resource.
*
* @param resource $resource
*
* @return static
*/
public static function fromResource($resource)
{
$image = new static();
$image->setResource($resource);
return $image;
}
}