/
basic_image.php
1942 lines (1676 loc) · 63.1 KB
/
basic_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
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Created by PhpStorm.
* User: markie
* Date: 2/25/2019
* Time: 5:12 PM
*/
namespace enriquez;
use Exception;
use League\ColorExtractor\Color;
use League\ColorExtractor\ColorExtractor;
use League\ColorExtractor\Palette;
class basic_image
{
const
ERR_FILE_NOT_FOUND = 1,
ERR_FONT_FILE = 2,
ERR_FREETYPE_NOT_ENABLED = 3,
ERR_GD_NOT_ENABLED = 4,
ERR_INVALID_COLOR = 5,
ERR_INVALID_DATA_URI = 6,
ERR_INVALID_IMAGE = 7,
ERR_LIB_NOT_LOADED = 8,
ERR_UNSUPPORTED_FORMAT = 9,
ERR_WEBP_NOT_ENABLED = 10,
ERR_WRITE = 11;
protected $image, $mimeType, $exif;
//////////////////////////////////////////////////////////////////////////////////////////////////
// Magic methods
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Creates a new SimpleImage object.
//
// $image (string) - An image file or a data URI to load.
//
public function __construct($image = null)
{
// Check for the required GD extension
if (extension_loaded('gd')) {
// Ignore JPEG warnings that cause imagecreatefromjpeg() to fail
ini_set('gd.jpeg_ignore_warning', 1);
} else {
throw new Exception('Required extension GD is not loaded.', self::ERR_GD_NOT_ENABLED);
}
// Load an image through the constructor
if (preg_match('/^data:(.*?);/', $image)) {
$this->fromDataUri($image);
} elseif ($image) {
$this->fromFile($image);
}
}
//
// Destroys the image resource
//
public function fromDataUri($uri)
{
// Basic formatting check
preg_match('/^data:(.*?);/', $uri, $matches);
if (!count($matches)) {
throw new Exception('Invalid data URI.', self::ERR_INVALID_DATA_URI);
}
// Determine mime type
$this->mimeType = $matches[1];
if (!preg_match('/^image\/(gif|jpeg|png)$/', $this->mimeType)) {
throw new Exception(
'Unsupported format: ' . $this->mimeType,
self::ERR_UNSUPPORTED_FORMAT
);
}
// Get image data
$uri = base64_decode(preg_replace('/^data:(.*?);base64,/', '', $uri));
$this->image = imagecreatefromstring($uri);
if (!$this->image) {
throw new Exception("Invalid image data.", self::ERR_INVALID_IMAGE);
}
return $this;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Loaders
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// load image from uri (link)
//
// $uri* (string) - A data URI.
//
// returns simple_image (SI) obj
//
public function fromFile($file)
{
// Check if the file exists and is readable. We're using fopen() instead of file_exists()
// because not all URL wrappers support the latter.
$handle = @fopen($file, 'r');
if ($handle === false) {
throw new Exception("File not found: $file", self::ERR_FILE_NOT_FOUND);
}
fclose($handle);
// Get image info
$info = getimagesize($file);
if ($info === false) {
throw new Exception("Invalid image file: $file", self::ERR_INVALID_IMAGE);
}
$this->mimeType = $info['mime'];
// Create image object from file
switch ($this->mimeType) {
case 'image/gif':
// Load the gif
$gif = imagecreatefromgif($file);
if ($gif) {
// Copy the gif over to a true color image to preserve its transparency. This is a
// workaround to prevent imagepalettetruecolor() from borking transparency.
$width = imagesx($gif);
$height = imagesy($gif);
$this->image = imagecreatetruecolor($width, $height);
$transparentColor = imagecolorallocatealpha($this->image, 0, 0, 0, 127);
imagecolortransparent($this->image, $transparentColor);
imagefill($this->image, 0, 0, $transparentColor);
imagecopy($this->image, $gif, 0, 0, 0, 0, $width, $height);
imagedestroy($gif);
}
break;
case 'image/jpeg':
$this->image = imagecreatefromjpeg($file);
break;
case 'image/png':
$this->image = imagecreatefrompng($file);
break;
case 'image/webp':
$this->image = imagecreatefromwebp($file);
break;
}
if (!$this->image) {
throw new Exception("Unsupported image: $file", self::ERR_UNSUPPORTED_FORMAT);
}
// Convert pallete images to true color images
imagepalettetotruecolor($this->image);
// Load exif data from JPEG images
if ($this->mimeType === 'image/jpeg' && function_exists('exif_read_data')) {
$this->exif = @exif_read_data($file);
}
return $this;
}
//
// Loads an image from a file.
//
// $file* (string) - The image file to load.
//
// Returns a SimpleImage object.
//
public static function darkenColor($color, $amount)
{
return self::adjustColor($color, -$amount, -$amount, -$amount, 0);
}
//
// Creates a new image.
//
// $width* (int) - The width of the image.
// $height* (int) - The height of the image.
// $color (string|array) - Optional fill color for the new image (default 'transparent').
//
// Returns a SimpleImage object.
//
public static function adjustColor($color, $red, $green, $blue, $alpha)
{
// Normalize to RGBA
$color = self::normalizeColor($color);
// Adjust each channel
return self::normalizeColor([
'red' => $color['red'] + $red,
'green' => $color['green'] + $green,
'blue' => $color['blue'] + $blue,
'alpha' => $color['alpha'] + $alpha
]);
}
//
// Creates a new image from a string.
//
// $string* (string) - The raw image data as a string. Example:
//
// $string = file_get_contents('image.jpg');
//
// Returns a SimpleImage object.
//
public static function normalizeColor($color)
{
// 140 CSS color names and hex values
$cssColors = [
'aliceblue' => '#f0f8ff', 'antiquewhite' => '#faebd7', 'aqua' => '#00ffff',
'aquamarine' => '#7fffd4', 'azure' => '#f0ffff', 'beige' => '#f5f5dc', 'bisque' => '#ffe4c4',
'black' => '#000000', 'blanchedalmond' => '#ffebcd', 'blue' => '#0000ff',
'blueviolet' => '#8a2be2', 'brown' => '#a52a2a', 'burlywood' => '#deb887',
'cadetblue' => '#5f9ea0', 'chartreuse' => '#7fff00', 'chocolate' => '#d2691e',
'coral' => '#ff7f50', 'cornflowerblue' => '#6495ed', 'cornsilk' => '#fff8dc',
'crimson' => '#dc143c', 'cyan' => '#00ffff', 'darkblue' => '#00008b', 'darkcyan' => '#008b8b',
'darkgoldenrod' => '#b8860b', 'darkgray' => '#a9a9a9', 'darkgrey' => '#a9a9a9',
'darkgreen' => '#006400', 'darkkhaki' => '#bdb76b', 'darkmagenta' => '#8b008b',
'darkolivegreen' => '#556b2f', 'darkorange' => '#ff8c00', 'darkorchid' => '#9932cc',
'darkred' => '#8b0000', 'darksalmon' => '#e9967a', 'darkseagreen' => '#8fbc8f',
'darkslateblue' => '#483d8b', 'darkslategray' => '#2f4f4f', 'darkslategrey' => '#2f4f4f',
'darkturquoise' => '#00ced1', 'darkviolet' => '#9400d3', 'deeppink' => '#ff1493',
'deepskyblue' => '#00bfff', 'dimgray' => '#696969', 'dimgrey' => '#696969',
'dodgerblue' => '#1e90ff', 'firebrick' => '#b22222', 'floralwhite' => '#fffaf0',
'forestgreen' => '#228b22', 'fuchsia' => '#ff00ff', 'gainsboro' => '#dcdcdc',
'ghostwhite' => '#f8f8ff', 'gold' => '#ffd700', 'goldenrod' => '#daa520', 'gray' => '#808080',
'grey' => '#808080', 'green' => '#008000', 'greenyellow' => '#adff2f',
'honeydew' => '#f0fff0', 'hotpink' => '#ff69b4', 'indianred ' => '#cd5c5c',
'indigo ' => '#4b0082', 'ivory' => '#fffff0', 'khaki' => '#f0e68c', 'lavender' => '#e6e6fa',
'lavenderblush' => '#fff0f5', 'lawngreen' => '#7cfc00', 'lemonchiffon' => '#fffacd',
'lightblue' => '#add8e6', 'lightcoral' => '#f08080', 'lightcyan' => '#e0ffff',
'lightgoldenrodyellow' => '#fafad2', 'lightgray' => '#d3d3d3', 'lightgrey' => '#d3d3d3',
'lightgreen' => '#90ee90', 'lightpink' => '#ffb6c1', 'lightsalmon' => '#ffa07a',
'lightseagreen' => '#20b2aa', 'lightskyblue' => '#87cefa', 'lightslategray' => '#778899',
'lightslategrey' => '#778899', 'lightsteelblue' => '#b0c4de', 'lightyellow' => '#ffffe0',
'lime' => '#00ff00', 'limegreen' => '#32cd32', 'linen' => '#faf0e6', 'magenta' => '#ff00ff',
'maroon' => '#800000', 'mediumaquamarine' => '#66cdaa', 'mediumblue' => '#0000cd',
'mediumorchid' => '#ba55d3', 'mediumpurple' => '#9370db', 'mediumseagreen' => '#3cb371',
'mediumslateblue' => '#7b68ee', 'mediumspringgreen' => '#00fa9a',
'mediumturquoise' => '#48d1cc', 'mediumvioletred' => '#c71585', 'midnightblue' => '#191970',
'mintcream' => '#f5fffa', 'mistyrose' => '#ffe4e1', 'moccasin' => '#ffe4b5',
'navajowhite' => '#ffdead', 'navy' => '#000080', 'oldlace' => '#fdf5e6', 'olive' => '#808000',
'olivedrab' => '#6b8e23', 'orange' => '#ffa500', 'orangered' => '#ff4500',
'orchid' => '#da70d6', 'palegoldenrod' => '#eee8aa', 'palegreen' => '#98fb98',
'paleturquoise' => '#afeeee', 'palevioletred' => '#db7093', 'papayawhip' => '#ffefd5',
'peachpuff' => '#ffdab9', 'peru' => '#cd853f', 'pink' => '#ffc0cb', 'plum' => '#dda0dd',
'powderblue' => '#b0e0e6', 'purple' => '#800080', 'rebeccapurple' => '#663399',
'red' => '#ff0000', 'rosybrown' => '#bc8f8f', 'royalblue' => '#4169e1',
'saddlebrown' => '#8b4513', 'salmon' => '#fa8072', 'sandybrown' => '#f4a460',
'seagreen' => '#2e8b57', 'seashell' => '#fff5ee', 'sienna' => '#a0522d',
'silver' => '#c0c0c0', 'skyblue' => '#87ceeb', 'slateblue' => '#6a5acd',
'slategray' => '#708090', 'slategrey' => '#708090', 'snow' => '#fffafa',
'springgreen' => '#00ff7f', 'steelblue' => '#4682b4', 'tan' => '#d2b48c', 'teal' => '#008080',
'thistle' => '#d8bfd8', 'tomato' => '#ff6347', 'turquoise' => '#40e0d0',
'violet' => '#ee82ee', 'wheat' => '#f5deb3', 'white' => '#ffffff', 'whitesmoke' => '#f5f5f5',
'yellow' => '#ffff00', 'yellowgreen' => '#9acd32'
];
// Parse alpha from '#fff|.5' and 'white|.5'
if (is_string($color) && strstr($color, '|')) {
$color = explode('|', $color);
$alpha = (float)$color[1];
$color = trim($color[0]);
} else {
$alpha = 1;
}
// Translate CSS color names to hex values
if (is_string($color) && array_key_exists(strtolower($color), $cssColors)) {
$color = $cssColors[strtolower($color)];
}
// Translate transparent keyword to a transparent color
if ($color === 'transparent') {
$color = ['red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 0];
}
// Convert hex values to RGBA
if (is_string($color)) {
// Remove #
$hex = preg_replace('/^#/', '', $color);
// Support short and standard hex codes
if (strlen($hex) === 3) {
list($red, $green, $blue) = [
$hex[0] . $hex[0],
$hex[1] . $hex[1],
$hex[2] . $hex[2]
];
} elseif (strlen($hex) === 6) {
list($red, $green, $blue) = [
$hex[0] . $hex[1],
$hex[2] . $hex[3],
$hex[4] . $hex[5]
];
} else {
throw new Exception("Invalid color value: $color", self::ERR_INVALID_COLOR);
}
// Turn color into an array
$color = [
'red' => hexdec($red),
'green' => hexdec($green),
'blue' => hexdec($blue),
'alpha' => $alpha
];
}
// Enforce color value ranges
if (is_array($color)) {
// RGB default to 0
$color['red'] = isset($color['red']) ? $color['red'] : 0;
$color['green'] = isset($color['green']) ? $color['green'] : 0;
$color['blue'] = isset($color['blue']) ? $color['blue'] : 0;
// Alpha defaults to 1
$color['alpha'] = isset($color['alpha']) ? $color['alpha'] : 1;
return [
'red' => (int)self::keepWithin((int)$color['red'], 0, 255),
'green' => (int)self::keepWithin((int)$color['green'], 0, 255),
'blue' => (int)self::keepWithin((int)$color['blue'], 0, 255),
'alpha' => self::keepWithin($color['alpha'], 0, 1)
];
}
throw new Exception("Invalid color value: $color", self::ERR_INVALID_COLOR);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Savers
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Generates an image.
//
// $mimeType (string) - The image format to output as a mime type (defaults to the original mime
// type).
// $quality (int) - Image quality as a percentage (default 100).
//
// Returns an array containing the image data and mime type.
//
private static function keepWithin($value, $min, $max)
{
if ($value < $min) return $min;
if ($value > $max) return $max;
return $value;
}
//
// Generates a data URI.
//
// $mimeType (string) - The image format to output as a mime type (defaults to the original mime
// type).
// $quality (int) - Image quality as a percentage (default 100).
//
// Returns a string containing a data URI.
//
public static function lightenColor($color, $amount)
{
return self::adjustColor($color, $amount, $amount, $amount, 0);
}
//
// Forces the image to be downloaded to the clients machine. Must be called before any output is
// sent to the screen.
//
// $filename* (string) - The filename (without path) to send to the client (e.g. 'image.jpeg').
// $mimeType (string) - The image format to output as a mime type (defaults to the original mime
// type).
// $quality (int) - Image quality as a percentage (default 100).
//
public function __destruct()
{
if ($this->image !== null && get_resource_type($this->image) === 'gd') {
imagedestroy($this->image);
}
}
//
// Writes the image to a file.
//
// $mimeType (string) - The image format to output as a mime type (defaults to the original mime
// type).
// $quality (int) - Image quality as a percentage (default 100).
//
// Returns a SimpleImage object.
//
public function fromNew($width, $height, $color = 'transparent')
{
$this->image = imagecreatetruecolor($width, $height);
// Use PNG for dynamically created images because it's lossless and supports transparency
$this->mimeType = 'image/png';
// Fill the image with color
$this->fill($color);
return $this;
}
//
// Outputs the image to the screen. Must be called before any output is sent to the screen.
//
// $mimeType (string) - The image format to output as a mime type (defaults to the original mime
// type).
// $quality (int) - Image quality as a percentage (default 100).
//
// Returns a SimpleImage object.
//
public function fill($color)
{
// Draw a filled rectangle over the entire image
$this->rectangle(0, 0, $this->getWidth(), $this->getHeight(), 'white', 'filled');
// Now flood it with the appropriate color
$color = $this->allocateColor($color);
imagefill($this->image, 0, 0, $color);
return $this;
}
//
// Generates an image string.
//
// $mimeType (string) - The image format to output as a mime type (defaults to the original mime
// type).
// $quality (int) - Image quality as a percentage (default 100).
//
// Returns a SimpleImage object.
//
public function rectangle($x1, $y1, $x2, $y2, $color, $thickness = 1)
{
// Allocate the color
$color = $this->allocateColor($color);
// Draw a rectangle
if ($thickness === 'filled') {
imagesetthickness($this->image, 1);
imagefilledrectangle($this->image, $x1, $y1, $x2, $y2, $color);
} else {
imagesetthickness($this->image, $thickness);
imagerectangle($this->image, $x1, $y1, $x2, $y2, $color);
}
return $this;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Ensures a numeric value is always within the min and max range.
//
// $value* (int|float) - A numeric value to test.
// $min* (int|float) - The minimum allowed value.
// $max* (int|float) - The maximum allowed value.
//
// Returns an int|float value.
//
private function allocateColor($color)
{
$color = self::normalizeColor($color);
// Was this color already allocated?
$index = imagecolorexactalpha(
$this->image,
$color['red'],
$color['green'],
$color['blue'],
127 - ($color['alpha'] * 127)
);
if ($index > -1) {
// Yes, return this color index
return $index;
}
// Allocate a new color index
return imagecolorallocatealpha(
$this->image,
$color['red'],
$color['green'],
$color['blue'],
127 - ($color['alpha'] * 127)
);
}
//
// Gets the image's current aspect ratio.
//
// Returns the aspect ratio as a float.
//
public function getWidth()
{
return (int)imagesx($this->image);
}
//
// Gets the image's exif data.
//
// Returns an array of exif data or null if no data is available.
//
public function getHeight()
{
return (int)imagesy($this->image);
}
//
// Gets the image's current height.
//
// Returns the height as an integer.
//
public function fromString($string)
{
return $this->fromFile('data://;base64,' . base64_encode($string));
}
//
// Gets the mime type of the loaded image.
//
// Returns a mime type string.
//
public function toDataUri($mimeType = null, $quality = 100)
{
$image = $this->generate($mimeType, $quality);
return 'data:' . $image['mimeType'] . ';base64,' . base64_encode($image['data']);
}
//
// Gets the image's current orientation.
//
// Returns a string: 'landscape', 'portrait', or 'square'
//
private function generate($mimeType = null, $quality = 100)
{
// Format defaults to the original mime type
$mimeType = $mimeType ?: $this->mimeType;
// Ensure quality is a valid integer
if ($quality === null) $quality = 100;
$quality = self::keepWithin((int)$quality, 0, 100);
// Capture output
ob_start();
// Generate the image
switch ($mimeType) {
case 'image/gif':
imagesavealpha($this->image, true);
imagegif($this->image, null);
break;
case 'image/jpeg':
imageinterlace($this->image, true);
imagejpeg($this->image, null, $quality);
break;
case 'image/png':
imagesavealpha($this->image, true);
imagepng($this->image, null, round(9 * $quality / 100));
break;
case 'image/webp':
// Not all versions of PHP will have webp support enabled
if (!function_exists('imagewebp')) {
throw new Exception(
'WEBP support is not enabled in your version of PHP.',
self::ERR_WEBP_NOT_ENABLED
);
}
imagesavealpha($this->image, true);
imagewebp($this->image, null, $quality);
break;
default:
throw new Exception('Unsupported format: ' . $mimeType, self::ERR_UNSUPPORTED_FORMAT);
}
// Stop capturing
$data = ob_get_contents();
ob_end_clean();
return [
'data' => $data,
'mimeType' => $mimeType
];
}
//
// Gets the image's current width.
//
// Returns the width as an integer.
//
public function toDownload($filename, $mimeType = null, $quality = 100)
{
$image = $this->generate($mimeType, $quality);
// Set download headers
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Description: File Transfer');
header('Content-Length: ' . strlen($image['data']));
header('Content-Transfer-Encoding: Binary');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"$filename\"");
echo $image['data'];
return $this;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Manipulation
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Same as PHP's imagecopymerge, but works with transparent images. Used internally for overlay.
//
public function toFile($file, $mimeType = null, $quality = 100)
{
$image = $this->generate($mimeType, $quality);
// Save the image to file
if (!file_put_contents($file, $image['data'])) {
throw new Exception("Failed to write image to file: $file", self::ERR_WRITE);
}
return $this;
}
//
// Rotates an image so the orientation will be correct based on its exif data. It is safe to call
// this method on images that don't have exif data (no changes will be made).
//
// Returns a SimpleImage object.
//
public function toScreen($mimeType = null, $quality = 100)
{
$image = $this->generate($mimeType, $quality);
// Output the image to stdout
header('Content-Type: ' . $image['mimeType']);
echo $image['data'];
return $this;
}
//
// Proportionally resize the image to fit inside a specific width and height.
//
// $maxWidth* (int) - The maximum width the image can be.
// $maxHeight* (int) - The maximum height the image can be.
//
// Returns a SimpleImage object.
//
public function toString($mimeType = null, $quality = 100)
{
return $this->generate($mimeType, $quality)['data'];
}
//
// Crop the image.
//
// $x1 - Top left x coordinate.
// $y1 - Top left y coordinate.
// $x2 - Bottom right x coordinate.
// $y2 - Bottom right x coordinate.
//
// Returns a SimpleImage object.
//
public function getMimeType()
{
return $this->mimeType;
}
//
// Applies a duotone filter to the image.
//
// $lightColor* (string|array) - The lightest color in the duotone.
// $darkColor* (string|array) - The darkest color in the duotone.
//
// Returns a SimpleImage object.
//
public function autoOrient()
{
$exif = $this->getExif();
if (!$exif || !isset($exif['Orientation'])) {
return $this;
}
switch ($exif['Orientation']) {
case 1: // Do nothing!
break;
case 2: // Flip horizontally
$this->flip('x');
break;
case 3: // Rotate 180 degrees
$this->rotate(180);
break;
case 4: // Flip vertically
$this->flip('y');
break;
case 5: // Rotate 90 degrees clockwise and flip vertically
$this->flip('y')->rotate(90);
break;
case 6: // Rotate 90 clockwise
$this->rotate(90);
break;
case 7: // Rotate 90 clockwise and flip horizontally
$this->flip('x')->rotate(90);
break;
case 8: // Rotate 90 counterclockwise
$this->rotate(-90);
break;
}
return $this;
}
//
// Proportionally resize the image to a specific height.
//
// **DEPRECATED:** This method was deprecated in version 3.2.2 and will be removed in version 4.0.
// Please use `resize(null, $height)` instead.
//
// $height* (int) - The height to resize the image to.
//
// Returns a SimpleImage object.
//
public function getExif()
{
return isset($this->exif) ? $this->exif : null;
}
//
// Proportionally resize the image to a specific width.
//
// **DEPRECATED:** This method was deprecated in version 3.2.2 and will be removed in version 4.0.
// Please use `resize($width, null)` instead.
//
// $width* (int) - The width to resize the image to.
//
// Returns a SimpleImage object.
//
public function flip($direction)
{
switch ($direction) {
case 'x':
imageflip($this->image, IMG_FLIP_HORIZONTAL);
break;
case 'y':
imageflip($this->image, IMG_FLIP_VERTICAL);
break;
case 'both':
imageflip($this->image, IMG_FLIP_BOTH);
break;
}
return $this;
}
//
// Flip the image horizontally or vertically.
//
// $direction* (string) - The direction to flip: x|y|both
//
// Returns a SimpleImage object.
//
public function rotate($angle, $backgroundColor = 'transparent')
{
// Rotate the image on a canvas with the desired background color
$backgroundColor = $this->allocateColor($backgroundColor);
$this->image = imagerotate(
$this->image,
-(self::keepWithin($angle, -360, 360)),
$backgroundColor
);
imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 127));
return $this;
}
//
// Reduces the image to a maximum number of colors.
//
// $max* (int) - The maximum number of colors to use.
// $dither (bool) - Whether or not to use a dithering effect (default true).
//
// Returns a SimpleImage object.
//
public function bestFit($maxWidth, $maxHeight)
{
// If the image already fits, there's nothing to do
if ($this->getWidth() <= $maxWidth && $this->getHeight() <= $maxHeight) {
return $this;
}
// Calculate max width or height based on orientation
if ($this->getOrientation() === 'portrait') {
$height = $maxHeight;
$width = $maxHeight * $this->getAspectRatio();
} else {
$width = $maxWidth;
$height = $maxWidth / $this->getAspectRatio();
}
// Reduce to max width
if ($width > $maxWidth) {
$width = $maxWidth;
$height = $width / $this->getAspectRatio();
}
// Reduce to max height
if ($height > $maxHeight) {
$height = $maxHeight;
$width = $height * $this->getAspectRatio();
}
return $this->resize($width, $height);
}
//
// Place an image on top of the current image.
//
// $overlay* (string|SimpleImage) - The image to overlay. This can be a filename, a data URI, or
// a SimpleImage object.
// $anchor (string) - The anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left',
// 'top right', 'bottom left', 'bottom right' (default 'center')
// $opacity (float) - The opacity level of the overlay 0-1 (default 1).
// $xOffset (int) - Horizontal offset in pixels (default 0).
// $yOffset (int) - Vertical offset in pixels (default 0).
//
// Returns a SimpleImage object.
//
public function getOrientation()
{
$width = $this->getWidth();
$height = $this->getHeight();
if ($width > $height) return 'landscape';
if ($width < $height) return 'portrait';
return 'square';
}
//
// Resize an image to the specified dimensions. If only one dimension is specified, the image will
// be resized proportionally.
//
// $width* (int) - The new image width.
// $height* (int) - The new image height.
//
// Returns a SimpleImage object.
//
public function getAspectRatio()
{
return $this->getWidth() / $this->getHeight();
}
//
// Rotates the image.
//
// $angle* (int) - The angle of rotation (-360 - 360).
// $backgroundColor (string|array) - The background color to use for the uncovered zone area
// after rotation (default 'transparent').
//
// Returns a SimpleImage object.
//
public function resize($width = null, $height = null)
{
// No dimentions specified
if (!$width && !$height) {
return $this;
}
// Resize to width
if ($width && !$height) {
$height = $width / $this->getAspectRatio();
}
// Resize to height
if (!$width && $height) {
$width = $height * $this->getAspectRatio();
}
// If the dimensions are the same, there's no need to resize
if ($this->getWidth() === $width && $this->getHeight() === $height) {
return $this;
}
// We can't use imagescale because it doesn't seem to preserve transparency properly. The
// workaround is to create a new truecolor image, allocate a transparent color, and copy the
// image over to it using imagecopyresampled.
$newImage = imagecreatetruecolor($width, $height);
$transparentColor = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
imagecolortransparent($newImage, $transparentColor);
imagefill($newImage, 0, 0, $transparentColor);
imagecopyresampled(
$newImage,
$this->image,
0, 0, 0, 0,
$width,
$height,
$this->getWidth(),
$this->getHeight()
);
// Swap out the new image
$this->image = $newImage;
return $this;
}
//
// Adds text to the image.
//
// $text* (string) - The desired text.
// $options (array) - An array of options.
// - fontFile* (string) - The TrueType (or compatible) font file to use.
// - size (int) - The size of the font in pixels (default 12).
// - color (string|array) - The text color (default black).
// - anchor (string) - The anchor point: 'center', 'top', 'bottom', 'left', 'right',
// 'top left', 'top right', 'bottom left', 'bottom right' (default 'center').
// - xOffset (int) - The horizontal offset in pixels (default 0).
// - yOffset (int) - The vertical offset in pixels (default 0).
// - shadow (array) - Text shadow params.
// - x* (int) - Horizontal offset in pixels.
// - y* (int) - Vertical offset in pixels.
// - color* (string|array) - The text shadow color.
// $boundary (array) - If passed, this variable will contain an array with coordinates that
// surround the text: [x1, y1, x2, y2, width, height]. This can be used for calculating the
// text's position after it gets added to the image.
//
// Returns a SimpleImage object.
//
function duotone($lightColor, $darkColor)
{
$lightColor = self::normalizeColor($lightColor);
$darkColor = self::normalizeColor($darkColor);
// Calculate averages between light and dark colors
$redAvg = $lightColor['red'] - $darkColor['red'];
$greenAvg = $lightColor['green'] - $darkColor['green'];
$blueAvg = $lightColor['blue'] - $darkColor['blue'];
// Create a matrix of all possible duotone colors based on gray values
$pixels = [];
for ($i = 0; $i <= 255; $i++) {
$grayAvg = $i / 255;
$pixels['red'][$i] = $darkColor['red'] + $grayAvg * $redAvg;
$pixels['green'][$i] = $darkColor['green'] + $grayAvg * $greenAvg;
$pixels['blue'][$i] = $darkColor['blue'] + $grayAvg * $blueAvg;
}
// Apply the filter pixel by pixel
for ($x = 0; $x < $this->getWidth(); $x++) {
for ($y = 0; $y < $this->getHeight(); $y++) {
$rgb = $this->getColorAt($x, $y);
$gray = min(255, round(0.299 * $rgb['red'] + 0.114 * $rgb['blue'] + 0.587 * $rgb['green']));
$this->dot($x, $y, [
'red' => $pixels['red'][$gray],
'green' => $pixels['green'][$gray],
'blue' => $pixels['blue'][$gray]
]);
}
}
return $this;
}