forked from mpdf/mpdf
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageProcessor.php
More file actions
1455 lines (1242 loc) · 44.5 KB
/
ImageProcessor.php
File metadata and controls
1455 lines (1242 loc) · 44.5 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
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
namespace Mpdf\Image;
use Mpdf\Cache;
use Mpdf\Color\ColorConverter;
use Mpdf\Color\ColorModeConverter;
use Mpdf\CssManager;
use Mpdf\Gif\Gif;
use Mpdf\Language\LanguageToFontInterface;
use Mpdf\Language\ScriptToLanguageInterface;
use Mpdf\Log\Context as LogContext;
use Mpdf\Mpdf;
use Mpdf\Otl;
use Mpdf\RemoteContentFetcher;
use Mpdf\SizeConverter;
use Psr\Log\LoggerInterface;
class ImageProcessor implements \Psr\Log\LoggerAwareInterface
{
/**
* @var \Mpdf\Mpdf
*/
private $mpdf;
/**
* @var \Mpdf\Otl
*/
private $otl;
/**
* @var \Mpdf\CssManager
*/
private $cssManager;
/**
* @var \Mpdf\SizeConverter
*/
private $sizeConverter;
/**
* @var \Mpdf\Color\ColorConverter
*/
private $colorConverter;
/**
* @var \Mpdf\Color\ColorModeConverter
*/
private $colorModeConverter;
/**
* @var \Mpdf\Cache
*/
private $cache;
/**
* @var \Mpdf\Image\ImageTypeGuesser
*/
private $guesser;
/**
* @var string[]
*/
private $failedImages;
/**
* @var \Mpdf\Image\Bmp
*/
private $bmp;
/**
* @var \Mpdf\Image\Wmf
*/
private $wmf;
/**
* @var \Mpdf\Language\LanguageToFontInterface
*/
private $languageToFont;
/**
* @var \Mpdf\Language\ScriptToLanguageInterface
*/
public $scriptToLanguage;
/**
* @var \Mpdf\RemoteContentFetcher
*/
private $remoteContentFetcher;
/**
* @var \Psr\Log\LoggerInterface
*/
public $logger;
public function __construct(
Mpdf $mpdf,
Otl $otl,
CssManager $cssManager,
SizeConverter $sizeConverter,
ColorConverter $colorConverter,
ColorModeConverter $colorModeConverter,
Cache $cache,
LanguageToFontInterface $languageToFont,
ScriptToLanguageInterface $scriptToLanguage,
RemoteContentFetcher $remoteContentFetcher,
LoggerInterface $logger
) {
$this->mpdf = $mpdf;
$this->otl = $otl;
$this->cssManager = $cssManager;
$this->sizeConverter = $sizeConverter;
$this->colorConverter = $colorConverter;
$this->colorModeConverter = $colorModeConverter;
$this->cache = $cache;
$this->languageToFont = $languageToFont;
$this->scriptToLanguage = $scriptToLanguage;
$this->remoteContentFetcher = $remoteContentFetcher;
$this->logger = $logger;
$this->guesser = new ImageTypeGuesser();
$this->failedImages = [];
}
/**
* @param \Psr\Log\LoggerInterface
*
* @return self
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
return $this;
}
public function getImage(&$file, $firsttime = true, $allowvector = true, $orig_srcpath = false, $interpolation = false)
{
/**
* Prevents insecure PHP deserialization through phar:// wrapper
* @see https://github.com/mpdf/mpdf/issues/949
*/
if ($this->hasBlacklistedStreamWrapper($file)) {
return $this->imageError($file, $firsttime, 'File contains an invalid stream. Only http://, https://, and file:// streams are valid.');
}
// mPDF 6
// firsttime i.e. whether to add to this->images - use false when calling iteratively
// Image Data passed directly as var:varname
$type = null;
$data = '';
if (preg_match('/var:\s*(.*)/', $file, $v)) {
if (!isset($this->mpdf->imageVars[$v[1]])) {
return $this->imageError($file, $firsttime, 'Unknown image variable');
}
$data = $this->mpdf->imageVars[$v[1]];
$file = md5($data);
}
if (preg_match('/data:image\/(gif|jpeg|png);base64,(.*)/', $file, $v)) {
$type = $v[1];
$data = base64_decode($v[2]);
$file = md5($data);
}
// mPDF 5.7.4 URLs
if ($firsttime && $file && strpos($file, 'data:') !== 0) {
$file = str_replace(' ', '%20', $file);
}
if ($firsttime && $orig_srcpath) {
// If orig_srcpath is a relative file path (and not a URL), then it needs to be URL decoded
if (strpos($orig_srcpath, 'data:') !== 0) {
$orig_srcpath = str_replace(' ', '%20', $orig_srcpath);
}
if (!preg_match('/^(http|ftp)/', $orig_srcpath)) {
$orig_srcpath = $this->urldecodeParts($orig_srcpath);
}
}
$ppUx = 0;
if ($orig_srcpath && isset($this->mpdf->images[$orig_srcpath])) {
$file = $orig_srcpath;
return $this->mpdf->images[$orig_srcpath];
}
if (isset($this->mpdf->images[$file])) {
return $this->mpdf->images[$file];
}
if ($orig_srcpath && isset($this->mpdf->formobjects[$orig_srcpath])) {
$file = $orig_srcpath;
return $this->mpdf->formobjects[$file];
}
if (isset($this->mpdf->formobjects[$file])) {
return $this->mpdf->formobjects[$file];
}
if ($firsttime && isset($this->failedImages[$file])) { // Save re-trying image URL's which have already failed
return $this->imageError($file, $firsttime, '');
}
if (empty($data)) {
$data = '';
if ($orig_srcpath && $this->mpdf->basepathIsLocal && $check = @fopen($orig_srcpath, 'rb')) {
fclose($check);
$file = $orig_srcpath;
$this->logger->debug(sprintf('Fetching (file_get_contents) content of file "%s" with local basepath', $file), ['context' => LogContext::REMOTE_CONTENT]);
$data = file_get_contents($file);
$type = $this->guesser->guess($data);
}
if (!$data && $check = @fopen($file, 'rb')) {
fclose($check);
$this->logger->debug(sprintf('Fetching (file_get_contents) content of file "%s" with non-local basepath', $file), ['context' => LogContext::REMOTE_CONTENT]);
$data = file_get_contents($file);
$type = $this->guesser->guess($data);
}
if ((!$data || !$type) && function_exists('curl_init')) { // mPDF 5.7.4
$data = $this->remoteContentFetcher->getFileContentsByCurl($file); // needs full url?? even on local (never needed for local)
if ($data) {
$type = $this->guesser->guess($data);
}
}
if ((!$data || !$type) && !ini_get('allow_url_fopen')) { // only worth trying if remote file and !ini_get('allow_url_fopen')
$data = $this->remoteContentFetcher->getFileContentsBySocket($file); // needs full url?? even on local (never needed for local)
if ($data) {
$type = $this->guesser->guess($data);
}
}
}
if (!$data) {
return $this->imageError($file, $firsttime, 'Could not find image file');
}
if ($type === null) {
$type = $this->guesser->guess($data);
}
if (($type === 'wmf' || $type === 'svg') && !$allowvector) {
return $this->imageError($file, $firsttime, 'WMF or SVG image file not supported in this context');
}
// SVG
if ($type === 'svg') {
$svg = new Svg($this->mpdf, $this->otl, $this->cssManager, $this, $this->sizeConverter, $this->colorConverter, $this->languageToFont, $this->scriptToLanguage);
$family = $this->mpdf->FontFamily;
$style = $this->mpdf->FontStyle;
$size = $this->mpdf->FontSizePt;
$info = $svg->ImageSVG($data);
// Restore font
if ($family) {
$this->mpdf->SetFont($family, $style, $size, false);
}
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing SVG file');
}
$info['type'] = 'svg';
$info['i'] = count($this->mpdf->formobjects) + 1;
$this->mpdf->formobjects[$file] = $info;
return $info;
}
// JPEG
if ($type === 'jpeg' || $type === 'jpg') {
$hdr = $this->jpgHeaderFromString($data);
if (!$hdr) {
return $this->imageError($file, $firsttime, 'Error parsing JPG header');
}
$a = $this->jpgDataFromHeader($hdr);
$channels = (int) $a[4];
$j = strpos($data, 'JFIF');
if ($j) {
// Read resolution
$unitSp = ord(substr($data, $j + 7, 1));
if ($unitSp > 0) {
$ppUx = $this->twoBytesToInt(substr($data, $j + 8, 2)); // horizontal pixels per meter, usually set to zero
if ($unitSp === 2) { // = dots per cm (if == 1 set as dpi)
$ppUx = round($ppUx / 10 * 25.4);
}
}
}
if ($a[2] === 'DeviceCMYK' && ($this->mpdf->restrictColorSpace === 2 || ($this->mpdf->PDFA && $this->mpdf->restrictColorSpace !== 3))) {
// convert to RGB image
if (!function_exists('gd_info')) {
throw new \Mpdf\MpdfException(sprintf('JPG image may not use CMYK color space (%s).', $file));
}
if ($this->mpdf->PDFA && !$this->mpdf->PDFAauto) {
$this->mpdf->PDFAXwarnings[] = sprintf('JPG image may not use CMYK color space - %s - (Image converted to RGB. NB This will alter the colour profile of the image.)', $file);
}
$im = @imagecreatefromstring($data);
if ($im) {
$tempfile = $this->cache->tempFilename('_tempImgPNG' . md5($file) . random_int(1, 10000) . '.png');
imageinterlace($im, false);
$check = @imagepng($im, $tempfile);
if (!$check) {
return $this->imageError($file, $firsttime, 'Error creating temporary file (' . $tempfile . ') whilst using GD library to parse JPG(CMYK) image');
}
$info = $this->getImage($tempfile, false);
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing temporary file (' . $tempfile . ') created with GD library to parse JPG(CMYK) image');
}
imagedestroy($im);
unlink($tempfile);
$info['type'] = 'jpg';
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;
$info['interpolation'] = $interpolation; // mPDF 6
$this->mpdf->images[$file] = $info;
}
return $info;
}
return $this->imageError($file, $firsttime, 'Error creating GD image file from JPG(CMYK) image');
}
if ($a[2] === 'DeviceRGB' && ($this->mpdf->PDFX || $this->mpdf->restrictColorSpace === 3)) {
// Convert to CMYK image stream - nominally returned as type='png'
$info = $this->convertImage($data, $a[2], 'DeviceCMYK', $a[0], $a[1], $ppUx, false);
if (($this->mpdf->PDFA && !$this->mpdf->PDFAauto) || ($this->mpdf->PDFX && !$this->mpdf->PDFXauto)) {
$this->mpdf->PDFAXwarnings[] = sprintf('JPG image may not use RGB color space - %s - (Image converted to CMYK. NB This will alter the colour profile of the image.)', $file);
}
} elseif (($a[2] === 'DeviceRGB' || $a[2] === 'DeviceCMYK') && $this->mpdf->restrictColorSpace === 1) {
// Convert to Grayscale image stream - nominally returned as type='png'
$info = $this->convertImage($data, $a[2], 'DeviceGray', $a[0], $a[1], $ppUx, false);
} else {
// mPDF 6 Detect Adobe APP14 Tag
//$pos = strpos($data, "\xFF\xEE\x00\x0EAdobe\0");
//if ($pos !== false) {
//}
// mPDF 6 ICC profile
$offset = 0;
$icc = [];
while (($pos = strpos($data, "ICC_PROFILE\0", $offset)) !== false) {
// get ICC sequence length
$length = $this->twoBytesToInt(substr($data, $pos - 2, 2)) - 16;
$sn = max(1, ord($data[$pos + 12]));
$nom = max(1, ord($data[$pos + 13]));
$icc[$sn - 1] = substr($data, $pos + 14, $length);
$offset = ($pos + 14 + $length);
}
// order and compact ICC segments
if (count($icc) > 0) {
ksort($icc);
$icc = implode('', $icc);
if (substr($icc, 36, 4) !== 'acsp') {
// invalid ICC profile
$icc = false;
}
$input = substr($icc, 16, 4);
$output = substr($icc, 20, 4);
// Ignore Color profiles for conversion to other colorspaces e.g. CMYK/Lab
if ($input !== 'RGB ' || $output !== 'XYZ ') {
$icc = false;
}
} else {
$icc = false;
}
$info = ['w' => $a[0], 'h' => $a[1], 'cs' => $a[2], 'bpc' => $a[3], 'f' => 'DCTDecode', 'data' => $data, 'type' => 'jpg', 'ch' => $channels, 'icc' => $icc];
if ($ppUx) {
$info['set-dpi'] = $ppUx;
}
}
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing or converting JPG image');
}
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;
$info['interpolation'] = $interpolation; // mPDF 6
$this->mpdf->images[$file] = $info;
}
return $info;
}
if ($type === 'png') {
// Check signature
if (strpos($data, chr(137) . 'PNG' . chr(13) . chr(10) . chr(26) . chr(10)) !== 0) {
return $this->imageError($file, $firsttime, 'Error parsing PNG identifier');
}
// Read header chunk
if (substr($data, 12, 4) !== 'IHDR') {
return $this->imageError($file, $firsttime, 'Incorrect PNG file (no IHDR block found)');
}
$w = $this->fourBytesToInt(substr($data, 16, 4));
$h = $this->fourBytesToInt(substr($data, 20, 4));
$bpc = ord(substr($data, 24, 1));
$errpng = false;
$pngalpha = false;
$channels = 0;
// if($bpc>8) { $errpng = 'not 8-bit depth'; } // mPDF 6 Allow through to be handled as native PNG
$ct = ord(substr($data, 25, 1));
if ($ct === 0) {
$colspace = 'DeviceGray';
$channels = 1;
} elseif ($ct === 2) {
$colspace = 'DeviceRGB';
$channels = 3;
} elseif ($ct === 3) {
$colspace = 'Indexed';
$channels = 1;
} elseif ($ct === 4) {
$colspace = 'DeviceGray';
$channels = 1;
$errpng = 'alpha channel';
$pngalpha = true;
} else {
$colspace = 'DeviceRGB';
$channels = 3;
$errpng = 'alpha channel';
$pngalpha = true;
}
if ($ct < 4 && strpos($data, 'tRNS') !== false) {
$errpng = 'transparency';
$pngalpha = true;
} // mPDF 6
if ($ct === 3 && strpos($data, 'iCCP') !== false) {
$errpng = 'indexed plus ICC';
} // mPDF 6
// $pngalpha is used as a FLAG of any kind of transparency which COULD be tranferred to an alpha channel
// incl. single-color tarnsparency, depending which type of handling occurs later
if (ord(substr($data, 26, 1)) !== 0) {
$errpng = 'compression method';
} // only 0 should be specified
if (ord(substr($data, 27, 1)) !== 0) {
$errpng = 'filter method';
} // only 0 should be specified
if (ord(substr($data, 28, 1)) !== 0) {
$errpng = 'interlaced file';
}
$j = strpos($data, 'pHYs');
if ($j) {
//Read resolution
$unitSp = ord(substr($data, $j + 12, 1));
if ($unitSp === 1) {
$ppUx = $this->fourBytesToInt(substr($data, $j + 4, 4)); // horizontal pixels per meter, usually set to zero
$ppUx = round($ppUx / 1000 * 25.4);
}
}
// mPDF 6 Gamma correction
$gamma = 0;
$gAMA = 0;
$j = strpos($data, 'gAMA');
if ($j && strpos($data, 'sRGB') === false) { // sRGB colorspace - overrides gAMA
$gAMA = $this->fourBytesToInt(substr($data, $j + 4, 4)); // Gamma value times 100000
$gAMA /= 100000;
// http://www.libpng.org/pub/png/spec/1.2/PNG-Encoders.html
// "If the source file's gamma value is greater than 1.0, it is probably a display system exponent,..."
// ("..and you should use its reciprocal for the PNG gamma.")
//if ($gAMA > 1) { $gAMA = 1/$gAMA; }
// (Some) Applications seem to ignore it... appearing how it was probably intended
// Test Case - image(s) on http://www.w3.org/TR/CSS21/intro.html - PNG has gAMA set as 1.45454
// Probably unintentional as mentioned above and should be 0.45454 which is 1 / 2.2
// Tested on Windows PC
// Firefox and Opera display gray as 234 (correct, but looks wrong)
// IE9 and Safari display gray as 193 (incorrect but looks right)
// See test different gamma chunks at http://www.libpng.org/pub/png/pngsuite-all-good.html
}
if ($gAMA) {
$gamma = 1 / $gAMA;
}
// Don't need to apply gamma correction if == default i.e. 2.2
if ($gamma > 2.15 && $gamma < 2.25) {
$gamma = 0;
}
// NOT supported at present
//$j = strpos($data,'sRGB'); // sRGB colorspace - overrides gAMA
//$j = strpos($data,'cHRM'); // Chromaticity and Whitepoint
// $firsttime added mPDF 6 so when PNG Grayscale with alpha using resrtictcolorspace to CMYK
// the alpha channel is sent through as secondtime as Indexed and should not be converted to CMYK
if ($firsttime && ($colspace === 'DeviceRGB' || $colspace === 'Indexed') && ($this->mpdf->PDFX || $this->mpdf->restrictColorSpace === 3)) {
// Convert to CMYK image stream - nominally returned as type='png'
$info = $this->convertImage($data, $colspace, 'DeviceCMYK', $w, $h, $ppUx, $pngalpha, $gamma, $ct); // mPDF 5.7.2 Gamma correction
if (($this->mpdf->PDFA && !$this->mpdf->PDFAauto) || ($this->mpdf->PDFX && !$this->mpdf->PDFXauto)) {
$this->mpdf->PDFAXwarnings[] = sprintf('PNG image may not use RGB color space - %s - (Image converted to CMYK. NB This will alter the colour profile of the image.)', $file);
}
} elseif ($firsttime && ($colspace === 'DeviceRGB' || $colspace === 'Indexed') && $this->mpdf->restrictColorSpace === 1) {
// $firsttime added mPDF 6 so when PNG Grayscale with alpha using resrtictcolorspace to CMYK
// the alpha channel is sent through as secondtime as Indexed and should not be converted to CMYK
// Convert to Grayscale image stream - nominally returned as type='png'
$info = $this->convertImage($data, $colspace, 'DeviceGray', $w, $h, $ppUx, $pngalpha, $gamma, $ct); // mPDF 5.7.2 Gamma correction
} elseif (($this->mpdf->PDFA || $this->mpdf->PDFX) && $pngalpha) {
// Remove alpha channel
if ($this->mpdf->restrictColorSpace === 1) { // Grayscale
$info = $this->convertImage($data, $colspace, 'DeviceGray', $w, $h, $ppUx, $pngalpha, $gamma, $ct); // mPDF 5.7.2 Gamma correction
} elseif ($this->mpdf->restrictColorSpace === 3) { // CMYK
$info = $this->convertImage($data, $colspace, 'DeviceCMYK', $w, $h, $ppUx, $pngalpha, $gamma, $ct); // mPDF 5.7.2 Gamma correction
} elseif ($this->mpdf->PDFA) { // RGB
$info = $this->convertImage($data, $colspace, 'DeviceRGB', $w, $h, $ppUx, $pngalpha, $gamma, $ct); // mPDF 5.7.2 Gamma correction
}
if (($this->mpdf->PDFA && !$this->mpdf->PDFAauto) || ($this->mpdf->PDFX && !$this->mpdf->PDFXauto)) {
$this->mpdf->PDFAXwarnings[] = sprintf('Transparency (alpha channel) not permitted in PDFA or PDFX files - %s - (Image converted to one without transparency.)', $file);
}
} elseif ($firsttime && ($errpng || $pngalpha || $gamma)) { // mPDF 5.7.2 Gamma correction
$gd = function_exists('gd_info') ? gd_info() : [];
if (!isset($gd['PNG Support'])) {
return $this->imageError($file, $firsttime, sprintf('GD library with PNG support required for image (%s)', $errpng));
}
$im = imagecreatefromstring($data);
if (!$im) {
return $this->imageError($file, $firsttime, sprintf('Error creating GD image from PNG file (%s)', $errpng));
}
$w = imagesx($im);
$h = imagesy($im);
$tempfile = $this->cache->tempFilename('_tempImgPNG' . md5($file) . random_int(1, 10000) . '.png');
// Alpha channel set (including using tRNS for Paletted images)
if ($pngalpha) {
if ($this->mpdf->PDFA) {
throw new \Mpdf\MpdfException(sprintf('PDFA1-b does not permit images with alpha channel transparency (%s).', $file));
}
$imgalpha = imagecreate($w, $h);
// generate gray scale pallete
for ($c = 0; $c < 256; ++$c) {
imagecolorallocate($imgalpha, $c, $c, $c);
}
// mPDF 6
if ($colspace === 'Indexed') { // generate Alpha channel values from tRNS
// Read transparency info
$p = strpos($data, 'tRNS');
if ($p) {
$n = $this->fourBytesToInt(substr($data, $p - 4, 4));
$transparency = substr($data, $p + 4, $n);
// ord($transparency{$index}) = the alpha value for that index
// generate alpha channel
for ($ypx = 0; $ypx < $h; ++$ypx) {
for ($xpx = 0; $xpx < $w; ++$xpx) {
$colorindex = imagecolorat($im, $xpx, $ypx);
if ($colorindex >= $n) {
$alpha = 255;
} else {
$alpha = ord($transparency{$colorindex});
} // 0-255
if ($alpha > 0) {
imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
}
}
}
}
} elseif ($ct === 0 || $ct === 2) { // generate Alpha channel values from tRNS
// Get transparency as array of RGB
$p = strpos($data, 'tRNS');
if ($p) {
$trns = '';
$n = $this->fourBytesToInt(substr($data, $p - 4, 4));
$t = substr($data, $p + 4, $n);
if ($colspace === 'DeviceGray') { // ct===0
$trns = [$this->translateValue(substr($t, 0, 2), $bpc)];
} else /* $colspace=='DeviceRGB' */ { // ct==2
$trns = [];
$trns[0] = $this->translateValue(substr($t, 0, 2), $bpc);
$trns[1] = $this->translateValue(substr($t, 2, 2), $bpc);
$trns[2] = $this->translateValue(substr($t, 4, 2), $bpc);
}
// generate alpha channel
for ($ypx = 0; $ypx < $h; ++$ypx) {
for ($xpx = 0; $xpx < $w; ++$xpx) {
$rgb = imagecolorat($im, $xpx, $ypx);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if ($colspace === 'DeviceGray' && $b == $trns[0]) {
$alpha = 0;
} elseif ($r == $trns[0] && $g == $trns[1] && $b == $trns[2]) {
$alpha = 0;
} else { // ct==2
$alpha = 255;
}
if ($alpha > 0) {
imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
}
}
}
}
} else {
// extract alpha channel
for ($ypx = 0; $ypx < $h; ++$ypx) {
for ($xpx = 0; $xpx < $w; ++$xpx) {
$alpha = (imagecolorat($im, $xpx, $ypx) & 0x7F000000) >> 24;
if ($alpha < 127) {
imagesetpixel($imgalpha, $xpx, $ypx, 255 - ($alpha * 2));
}
}
}
}
// NB This must happen after the Alpha channel is extracted
// imagegammacorrect() removes the alpha channel data in $im - (I think this is a bug in PHP)
if ($gamma) {
imagegammacorrect($im, $gamma, 2.2);
}
$tempfile_alpha = $this->cache->tempFilename('_tempMskPNG' . md5($file) . random_int(1, 10000) . '.png');
$check = @imagepng($imgalpha, $tempfile_alpha);
if (!$check) {
return $this->imageError($file, $firsttime, 'Failed to create temporary image file (' . $tempfile_alpha . ') parsing PNG image with alpha channel (' . $errpng . ')');
}
imagedestroy($imgalpha);
// extract image without alpha channel
$imgplain = imagecreatetruecolor($w, $h);
imagealphablending($imgplain, false); // mPDF 5.7.2
imagecopy($imgplain, $im, 0, 0, 0, 0, $w, $h);
// create temp image file
$check = @imagepng($imgplain, $tempfile);
if (!$check) {
return $this->imageError($file, $firsttime, 'Failed to create temporary image file (' . $tempfile . ') parsing PNG image with alpha channel (' . $errpng . ')');
}
imagedestroy($imgplain);
// embed mask image
$minfo = $this->getImage($tempfile_alpha, false);
unlink($tempfile_alpha);
if (!$minfo) {
return $this->imageError($file, $firsttime, 'Error parsing temporary file (' . $tempfile_alpha . ') created with GD library to parse PNG image');
}
$imgmask = count($this->mpdf->images) + 1;
$minfo['cs'] = 'DeviceGray';
$minfo['i'] = $imgmask;
$this->mpdf->images[$tempfile_alpha] = $minfo;
// embed image, masked with previously embedded mask
$info = $this->getImage($tempfile, false);
unlink($tempfile);
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing temporary file (' . $tempfile . ') created with GD library to parse PNG image');
}
$info['masked'] = $imgmask;
if ($ppUx) {
$info['set-dpi'] = $ppUx;
}
$info['type'] = 'png';
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;
$info['interpolation'] = $interpolation; // mPDF 6
$this->mpdf->images[$file] = $info;
}
return $info;
}
// No alpha/transparency set (but cannot read directly because e.g. bit-depth != 8, interlaced etc)
// ICC profile
$icc = false;
$p = strpos($data, 'iCCP');
if ($p && $colspace === "Indexed") { // Cannot have ICC profile and Indexed together
$p += 4;
$n = $this->fourBytesToInt(substr($data, ($p - 8), 4));
$nullsep = strpos(substr($data, $p, 80), chr(0));
$icc = substr($data, ($p + $nullsep + 2), ($n - ($nullsep + 2)));
$icc = @gzuncompress($icc); // Ignored if fails
if ($icc) {
if (substr($icc, 36, 4) !== 'acsp') {
$icc = false;
} // invalid ICC profile
else {
$input = substr($icc, 16, 4);
$output = substr($icc, 20, 4);
// Ignore Color profiles for conversion to other colorspaces e.g. CMYK/Lab
if ($input !== 'RGB ' || $output !== 'XYZ ') {
$icc = false;
}
}
}
// Convert to RGB colorspace so can use ICC Profile
if ($icc) {
imagepalettetotruecolor($im);
$colspace = 'DeviceRGB';
$channels = 3;
}
}
if ($gamma) {
imagegammacorrect($im, $gamma, 2.2);
}
imagealphablending($im, false);
imagesavealpha($im, false);
imageinterlace($im, false);
$check = @imagepng($im, $tempfile);
if (!$check) {
return $this->imageError($file, $firsttime, 'Failed to create temporary image file (' . $tempfile . ') parsing PNG image (' . $errpng . ')');
}
imagedestroy($im);
$info = $this->getImage($tempfile, false);
unlink($tempfile);
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing temporary file (' . $tempfile . ') created with GD library to parse PNG image');
}
if ($ppUx) {
$info['set-dpi'] = $ppUx;
}
$info['type'] = 'png';
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;
$info['interpolation'] = $interpolation; // mPDF 6
if ($icc) {
$info['ch'] = $channels;
$info['icc'] = $icc;
}
$this->mpdf->images[$file] = $info;
}
return $info;
} else { // PNG image with no need to convert alph channels, bpc <> 8 etc.
$parms = '/DecodeParms <</Predictor 15 /Colors ' . $channels . ' /BitsPerComponent ' . $bpc . ' /Columns ' . $w . '>>';
//Scan chunks looking for palette, transparency and image data
$pal = '';
$trns = '';
$pngdata = '';
$icc = false;
$p = 33;
do {
$n = $this->fourBytesToInt(substr($data, $p, 4));
$p += 4;
$type = substr($data, $p, 4);
$p += 4;
if ($type === 'PLTE') {
//Read palette
$pal = substr($data, $p, $n);
$p += $n;
$p += 4;
} elseif ($type === 'tRNS') {
//Read transparency info
$t = substr($data, $p, $n);
$p += $n;
if ($ct === 0) {
$trns = [ord(substr($t, 1, 1))];
} elseif ($ct === 2) {
$trns = [ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1))];
} else {
$pos = strpos($t, chr(0));
if (is_int($pos)) {
$trns = [$pos];
}
}
$p += 4;
} elseif ($type === 'IDAT') {
$pngdata.=substr($data, $p, $n);
$p += $n;
$p += 4;
} elseif ($type === 'iCCP') {
$nullsep = strpos(substr($data, $p, 80), chr(0));
$icc = substr($data, $p + $nullsep + 2, $n - ($nullsep + 2));
$icc = @gzuncompress($icc); // Ignored if fails
if ($icc) {
if (substr($icc, 36, 4) !== 'acsp') {
$icc = false;
} // invalid ICC profile
else {
$input = substr($icc, 16, 4);
$output = substr($icc, 20, 4);
// Ignore Color profiles for conversion to other colorspaces e.g. CMYK/Lab
if ($input !== 'RGB ' || $output !== 'XYZ ') {
$icc = false;
}
}
}
$p += $n;
$p += 4;
} elseif ($type === 'IEND') {
break;
} elseif (preg_match('/[a-zA-Z]{4}/', $type)) {
$p += $n + 4;
} else {
return $this->imageError($file, $firsttime, 'Error parsing PNG image data');
}
} while ($n);
if (!$pngdata) {
return $this->imageError($file, $firsttime, 'Error parsing PNG image data - no IDAT data found');
}
if ($colspace === 'Indexed' && empty($pal)) {
return $this->imageError($file, $firsttime, 'Error parsing PNG image data - missing colour palette');
}
if ($colspace === 'Indexed' && $icc) {
$icc = false;
} // mPDF 6 cannot have ICC profile and Indexed in a PDF document as both use the colorspace tag.
$info = ['w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $pngdata, 'ch' => $channels, 'icc' => $icc];
$info['type'] = 'png';
if ($ppUx) {
$info['set-dpi'] = $ppUx;
}
}
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing or converting PNG image');
}
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;
$info['interpolation'] = $interpolation; // mPDF 6
$this->mpdf->images[$file] = $info;
}
return $info;
} elseif ($type === 'gif') { // GIF
if (function_exists('gd_info')) {
$gd = gd_info();
} else {
$gd = [];
}
if (isset($gd['GIF Read Support']) && $gd['GIF Read Support']) {
$im = @imagecreatefromstring($data);
if ($im) {
$tempfile = $this->cache->tempFilename('_tempImgPNG' . md5($file) . random_int(1, 10000) . '.png');
imagealphablending($im, false);
imagesavealpha($im, false);
imageinterlace($im, false);
if (!is_writable($tempfile)) {
ob_start();
$check = @imagepng($im);
if (!$check) {
return $this->imageError($file, $firsttime, 'Error creating temporary image object whilst using GD library to parse GIF image');
}
$this->mpdf->imageVars['tempImage'] = ob_get_contents();
$tempimglnk = 'var:tempImage';
ob_end_clean();
$info = $this->getImage($tempimglnk, false);
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing temporary file image object created with GD library to parse GIF image');
}
imagedestroy($im);
} else {
$check = @imagepng($im, $tempfile);
if (!$check) {
return $this->imageError($file, $firsttime, 'Error creating temporary file (' . $tempfile . ') whilst using GD library to parse GIF image');
}
$info = $this->getImage($tempfile, false);
if (!$info) {
return $this->imageError($file, $firsttime, 'Error parsing temporary file (' . $tempfile . ') created with GD library to parse GIF image');
}
imagedestroy($im);
unlink($tempfile);
}
$info['type'] = 'gif';
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;
$info['interpolation'] = $interpolation; // mPDF 6
$this->mpdf->images[$file] = $info;
}
return $info;
}
return $this->imageError($file, $firsttime, 'Error creating GD image file from GIF image');
}
$gif = new Gif();
$h = 0;
$w = 0;
$gif->loadFile($data, 0);
$nColors = 0;
$bgColor = -1;
$colspace = 'DeviceGray';
$pal = '';
if (isset($gif->m_img->m_gih->m_bLocalClr) && $gif->m_img->m_gih->m_bLocalClr) {
$nColors = $gif->m_img->m_gih->m_nTableSize;
$pal = $gif->m_img->m_gih->m_colorTable->toString();
if ((isset($bgColor)) && $bgColor !== -1) { // mPDF 5.7.3
$bgColor = $gif->m_img->m_gih->m_colorTable->colorIndex($bgColor);
}
$colspace = 'Indexed';
} elseif (isset($gif->m_gfh->m_bGlobalClr) && $gif->m_gfh->m_bGlobalClr) {
$nColors = $gif->m_gfh->m_nTableSize;
$pal = $gif->m_gfh->m_colorTable->toString();
if ((isset($bgColor)) && $bgColor != -1) {
$bgColor = $gif->m_gfh->m_colorTable->colorIndex($bgColor);
}
$colspace = 'Indexed';
}
$trns = '';
if (isset($gif->m_img->m_bTrans) && $gif->m_img->m_bTrans && ($nColors > 0)) {
$trns = [$gif->m_img->m_nTrans];
}
$gifdata = $gif->m_img->m_data;
$w = $gif->m_gfh->m_nWidth;
$h = $gif->m_gfh->m_nHeight;
$gif->ClearData();
if ($colspace === 'Indexed' && empty($pal)) {
return $this->imageError($file, $firsttime, 'Error parsing GIF image - missing colour palette');
}
if ($this->mpdf->compress) {
$gifdata = $this->gzCompress($gifdata);
$info = ['w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => 8, 'f' => 'FlateDecode', 'pal' => $pal, 'trns' => $trns, 'data' => $gifdata];
} else {
$info = ['w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => 8, 'pal' => $pal, 'trns' => $trns, 'data' => $gifdata];
}
$info['type'] = 'gif';
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;
$info['interpolation'] = $interpolation; // mPDF 6
$this->mpdf->images[$file] = $info;
}
return $info;
} elseif ($type === 'bmp') {
if ($this->bmp === null) {
$this->bmp = new Bmp($this->mpdf);
}
$info = $this->bmp->_getBMPimage($data, $file);
if (isset($info['error'])) {
return $this->imageError($file, $firsttime, $info['error']);
}
if ($firsttime) {
$info['i'] = count($this->mpdf->images) + 1;