]> git.mxchange.org Git - friendica.git/blob - src/Object/Image.php
Hopefully fix "Interlace handling should be turned on when using png_read_image"
[friendica.git] / src / Object / Image.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Object;
23
24 use Exception;
25 use Friendica\DI;
26 use Friendica\Util\Images;
27 use Imagick;
28 use ImagickDraw;
29 use ImagickPixel;
30 use GDImage;
31 use kornrunner\Blurhash\Blurhash;
32
33 /**
34  * Class to handle images
35  */
36 class Image
37 {
38         /** @var GDImage|Imagick|resource */
39         private $image;
40
41         /*
42          * Put back gd stuff, not everybody have Imagick
43          */
44         private $imagick;
45         private $width;
46         private $height;
47         private $valid;
48         private $type;
49         private $types;
50
51         /**
52          * Constructor
53          *
54          * @param string $data Image data
55          * @param string $type optional, default null
56          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57          * @throws \ImagickException
58          */
59         public function __construct(string $data, string $type = null)
60         {
61                 $this->imagick = class_exists('Imagick');
62                 $this->types = Images::supportedTypes();
63                 if (!array_key_exists($type, $this->types)) {
64                         $type = 'image/jpeg';
65                 }
66                 $this->type = $type;
67
68                 if ($this->isImagick() && (empty($data) || $this->loadData($data))) {
69                         $this->valid = !empty($data);
70                         return;
71                 } else {
72                         // Failed to load with Imagick, fallback
73                         $this->imagick = false;
74                 }
75                 $this->loadData($data);
76         }
77
78         /**
79          * Destructor
80          *
81          * @return void
82          */
83         public function __destruct()
84         {
85                 if ($this->image) {
86                         if ($this->isImagick()) {
87                                 $this->image->clear();
88                                 $this->image->destroy();
89                                 return;
90                         }
91                         if (is_resource($this->image)) {
92                                 imagedestroy($this->image);
93                         }
94                 }
95         }
96
97         /**
98          * @return boolean
99          */
100         public function isImagick()
101         {
102                 return $this->imagick;
103         }
104
105         /**
106          * Loads image data into handler class
107          *
108          * @param string $data Image data
109          * @return boolean Success
110          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
111          * @throws \ImagickException
112          */
113         private function loadData(string $data): bool
114         {
115                 if ($this->isImagick()) {
116                         $this->image = new Imagick();
117                         try {
118                                 $this->image->readImageBlob($data);
119                         } catch (Exception $e) {
120                                 // Imagick couldn't use the data
121                                 return false;
122                         }
123
124                         /*
125                          * Setup the image to the format it will be saved to
126                          */
127                         $map = Images::getFormatsMap();
128                         $format = $map[$this->type];
129                         $this->image->setFormat($format);
130
131                         // Always coalesce, if it is not a multi-frame image it won't hurt anyway
132                         try {
133                                 $this->image = $this->image->coalesceImages();
134                         } catch (Exception $e) {
135                                 return false;
136                         }
137
138                         /*
139                          * setup the compression here, so we'll do it only once
140                          */
141                         switch ($this->getType()) {
142                                 case 'image/png':
143                                         $quality = DI::config()->get('system', 'png_quality');
144                                         /*
145                                          * From http://www.imagemagick.org/script/command-line-options.php#quality:
146                                          *
147                                          * 'For the MNG and PNG image formats, the quality value sets
148                                          * the zlib compression level (quality / 10) and filter-type (quality % 10).
149                                          * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
150                                          * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
151                                          */
152                                         $quality = $quality * 10;
153                                         $this->image->setCompressionQuality($quality);
154                                         break;
155
156                                 case 'image/jpg':
157                                 case 'image/jpeg':
158                                         $quality = DI::config()->get('system', 'jpeg_quality');
159                                         $this->image->setCompressionQuality($quality);
160                         }
161
162                         $this->width  = $this->image->getImageWidth();
163                         $this->height = $this->image->getImageHeight();
164                         $this->valid  = !empty($this->image);
165
166                         return $this->valid;
167                 }
168
169                 $this->valid = false;
170                 try {
171                         $this->image = @imagecreatefromstring($data);
172                         if ($this->image !== false) {
173                                 $this->width  = imagesx($this->image);
174                                 $this->height = imagesy($this->image);
175                                 $this->valid  = true;
176                                 imagealphablending($this->image, false);
177                                 imagesavealpha($this->image, true);
178                                 imageinterlace($this->image, true);
179
180                                 return true;
181                         }
182                 } catch (\Throwable $error) {
183                         /** @see https://github.com/php/doc-en/commit/d09a881a8e9059d11e756ee59d75bf404d6941ed */
184                         if (strstr($error->getMessage(), "gd-webp cannot allocate temporary buffer")) {
185                                 DI::logger()->notice('Image is probably animated and therefore unsupported', ['error' => $error]);
186                         } else {
187                                 DI::logger()->warning('Unexpected throwable.', ['error' => $error]);
188                         }
189                 }
190
191                 return false;
192         }
193
194         /**
195          * @return boolean
196          */
197         public function isValid(): bool
198         {
199                 if ($this->isImagick()) {
200                         return !empty($this->image);
201                 }
202                 return $this->valid;
203         }
204
205         /**
206          * @return mixed
207          */
208         public function getWidth()
209         {
210                 if (!$this->isValid()) {
211                         return false;
212                 }
213
214                 return $this->width;
215         }
216
217         /**
218          * @return mixed
219          */
220         public function getHeight()
221         {
222                 if (!$this->isValid()) {
223                         return false;
224                 }
225
226                 return $this->height;
227         }
228
229         /**
230          * @return mixed
231          */
232         public function getImage()
233         {
234                 if (!$this->isValid()) {
235                         return false;
236                 }
237
238                 if ($this->isImagick()) {
239                         try {
240                                 /* Clean it */
241                                 $this->image = $this->image->deconstructImages();
242                                 return $this->image;
243                         } catch (Exception $e) {
244                                 return false;
245                         }
246                 }
247                 return $this->image;
248         }
249
250         /**
251          * @return mixed
252          */
253         public function getType()
254         {
255                 if (!$this->isValid()) {
256                         return false;
257                 }
258
259                 return $this->type;
260         }
261
262         /**
263          * @return mixed
264          */
265         public function getExt()
266         {
267                 if (!$this->isValid()) {
268                         return false;
269                 }
270
271                 return $this->types[$this->getType()];
272         }
273
274         /**
275          * Scales image down
276          *
277          * @param integer $max max dimension
278          * @return mixed
279          */
280         public function scaleDown(int $max)
281         {
282                 if (!$this->isValid()) {
283                         return false;
284                 }
285
286                 $width = $this->getWidth();
287                 $height = $this->getHeight();
288
289                 $scale = Images::getScalingDimensions($width, $height, $max);
290                 if ($scale) {
291                         return $this->scale($scale['width'], $scale['height']);
292                 } else {
293                         return false;
294                 }
295
296         }
297
298         /**
299          * Rotates image
300          *
301          * @param integer $degrees degrees to rotate image
302          * @return mixed
303          */
304         public function rotate(int $degrees)
305         {
306                 if (!$this->isValid()) {
307                         return false;
308                 }
309
310                 if ($this->isImagick()) {
311                         $this->image->setFirstIterator();
312                         do {
313                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
314                         } while ($this->image->nextImage());
315
316                         $this->width  = $this->image->getImageWidth();
317                         $this->height = $this->image->getImageHeight();
318                         return;
319                 }
320
321                 // if script dies at this point check memory_limit setting in php.ini
322                 $this->image  = imagerotate($this->image, $degrees, 0);
323                 $this->width  = imagesx($this->image);
324                 $this->height = imagesy($this->image);
325         }
326
327         /**
328          * Flips image
329          *
330          * @param boolean $horiz optional, default true
331          * @param boolean $vert  optional, default false
332          * @return mixed
333          */
334         public function flip(bool $horiz = true, bool $vert = false)
335         {
336                 if (!$this->isValid()) {
337                         return false;
338                 }
339
340                 if ($this->isImagick()) {
341                         $this->image->setFirstIterator();
342                         do {
343                                 if ($horiz) {
344                                         $this->image->flipImage();
345                                 }
346                                 if ($vert) {
347                                         $this->image->flopImage();
348                                 }
349                         } while ($this->image->nextImage());
350                         return;
351                 }
352
353                 $w = imagesx($this->image);
354                 $h = imagesy($this->image);
355                 $flipped = imagecreate($w, $h);
356                 if ($horiz) {
357                         for ($x = 0; $x < $w; $x++) {
358                                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
359                         }
360                 }
361                 if ($vert) {
362                         for ($y = 0; $y < $h; $y++) {
363                                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
364                         }
365                 }
366                 $this->image = $flipped;
367         }
368
369         /**
370          * Fixes orientation and maybe returns EXIF data (?)
371          *
372          * @param string $filename Filename
373          * @return mixed
374          */
375         public function orient(string $filename)
376         {
377                 if ($this->isImagick()) {
378                         // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
379                         $orientation = $this->image->getImageOrientation();
380                         switch ($orientation) {
381                                 case Imagick::ORIENTATION_BOTTOMRIGHT:
382                                         $this->rotate(180);
383                                         break;
384                                 case Imagick::ORIENTATION_RIGHTTOP:
385                                         $this->rotate(-90);
386                                         break;
387                                 case Imagick::ORIENTATION_LEFTBOTTOM:
388                                         $this->rotate(90);
389                                         break;
390                         }
391
392                         $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
393                         return true;
394                 }
395                 // based off comment on http://php.net/manual/en/function.imagerotate.php
396
397                 if (!$this->isValid()) {
398                         return false;
399                 }
400
401                 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
402                         return;
403                 }
404
405                 $exif = @exif_read_data($filename, null, true);
406                 if (!$exif) {
407                         return;
408                 }
409
410                 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
411
412                 switch ($ort) {
413                         case 1: // nothing
414                                 break;
415
416                         case 2: // horizontal flip
417                                 $this->flip();
418                                 break;
419
420                         case 3: // 180 rotate left
421                                 $this->rotate(180);
422                                 break;
423
424                         case 4: // vertical flip
425                                 $this->flip(false, true);
426                                 break;
427
428                         case 5: // vertical flip + 90 rotate right
429                                 $this->flip(false, true);
430                                 $this->rotate(-90);
431                                 break;
432
433                         case 6: // 90 rotate right
434                                 $this->rotate(-90);
435                                 break;
436
437                         case 7: // horizontal flip + 90 rotate right
438                                 $this->flip();
439                                 $this->rotate(-90);
440                                 break;
441
442                         case 8: // 90 rotate left
443                                 $this->rotate(90);
444                                 break;
445                 }
446
447                 return $exif;
448         }
449
450         /**
451          * Rescales image to minimum size
452          *
453          * @param integer $min Minimum dimension
454          * @return mixed
455          */
456         public function scaleUp(int $min)
457         {
458                 if (!$this->isValid()) {
459                         return false;
460                 }
461
462                 $width = $this->getWidth();
463                 $height = $this->getHeight();
464
465                 if ((!$width)|| (!$height)) {
466                         return false;
467                 }
468
469                 if ($width < $min && $height < $min) {
470                         if ($width > $height) {
471                                 $dest_width = $min;
472                                 $dest_height = intval(($height * $min) / $width);
473                         } else {
474                                 $dest_width = intval(($width * $min) / $height);
475                                 $dest_height = $min;
476                         }
477                 } else {
478                         if ($width < $min) {
479                                 $dest_width = $min;
480                                 $dest_height = intval(($height * $min) / $width);
481                         } else {
482                                 if ($height < $min) {
483                                         $dest_width = intval(($width * $min) / $height);
484                                         $dest_height = $min;
485                                 } else {
486                                         $dest_width = $width;
487                                         $dest_height = $height;
488                                 }
489                         }
490                 }
491
492                 return $this->scale($dest_width, $dest_height);
493         }
494
495         /**
496          * Scales image to square
497          *
498          * @param integer $dim Dimension
499          * @return mixed
500          */
501         public function scaleToSquare(int $dim)
502         {
503                 if (!$this->isValid()) {
504                         return false;
505                 }
506
507                 return $this->scale($dim, $dim);
508         }
509
510         /**
511          * Scale image to target dimensions
512          *
513          * @param int $dest_width Destination width
514          * @param int $dest_height Destination height
515          * @return boolean Success
516          */
517         private function scale(int $dest_width, int $dest_height): bool
518         {
519                 if (!$this->isValid()) {
520                         return false;
521                 }
522
523                 if ($this->isImagick()) {
524                         /*
525                          * If it is not animated, there will be only one iteration here,
526                          * so don't bother checking
527                          */
528                         // Don't forget to go back to the first frame
529                         $this->image->setFirstIterator();
530                         do {
531                                 // FIXME - implement horizontal bias for scaling as in following GD functions
532                                 // to allow very tall images to be constrained only horizontally.
533                                 try {
534                                         $this->image->scaleImage($dest_width, $dest_height);
535                                 } catch (Exception $e) {
536                                         // Imagick couldn't use the data
537                                         return false;
538                                 }
539                         } while ($this->image->nextImage());
540
541                         $this->width  = $this->image->getImageWidth();
542                         $this->height = $this->image->getImageHeight();
543                 } else {
544                         $dest = imagecreatetruecolor($dest_width, $dest_height);
545                         imagealphablending($dest, false);
546                         imagesavealpha($dest, true);
547                         imageinterlace($dest, true);
548
549                         if ($this->type=='image/png') {
550                                 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
551                         }
552
553                         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
554
555                         if ($this->image) {
556                                 imagedestroy($this->image);
557                         }
558
559                         $this->image = $dest;
560                         $this->width  = imagesx($this->image);
561                         $this->height = imagesy($this->image);
562                 }
563
564                 return true;
565         }
566
567         /**
568          * Convert a GIF to a PNG to make it static
569          *
570          * @return void
571          */
572         public function toStatic()
573         {
574                 if ($this->type != 'image/gif') {
575                         return;
576                 }
577
578                 if ($this->isImagick()) {
579                         $this->type == 'image/png';
580                         $this->image->setFormat('png');
581                 }
582         }
583
584         /**
585          * Crops image
586          *
587          * @param integer $max maximum
588          * @param integer $x   x coordinate
589          * @param integer $y   y coordinate
590          * @param integer $w   width
591          * @param integer $h   height
592          * @return mixed
593          */
594         public function crop(int $max, int $x, int $y, int $w, int $h)
595         {
596                 if (!$this->isValid()) {
597                         return false;
598                 }
599
600                 if ($this->isImagick()) {
601                         $this->image->setFirstIterator();
602                         do {
603                                 $this->image->cropImage($w, $h, $x, $y);
604                                 /*
605                                  * We need to remove the canvas,
606                                  * or the image is not resized to the crop:
607                                  * http://php.net/manual/en/imagick.cropimage.php#97232
608                                  */
609                                 $this->image->setImagePage(0, 0, 0, 0);
610                         } while ($this->image->nextImage());
611                         return $this->scaleDown($max);
612                 }
613
614                 $dest = imagecreatetruecolor($max, $max);
615                 imagealphablending($dest, false);
616                 imagesavealpha($dest, true);
617                 imageinterlace($dest, true);
618                 if ($this->type=='image/png') {
619                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
620                 }
621                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
622                 if ($this->image) {
623                         imagedestroy($this->image);
624                 }
625                 $this->image  = $dest;
626                 $this->width  = imagesx($this->image);
627                 $this->height = imagesy($this->image);
628
629                 // All successful
630                 return true;
631         }
632
633         /**
634          * Magic method allowing string casting of an Image object
635          *
636          * Ex: $data = $Image->asString();
637          * can be replaced by
638          * $data = (string) $Image;
639          *
640          * @return string
641          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
642          */
643         public function __toString(): string
644         {
645                 return (string) $this->asString();
646         }
647
648         /**
649          * Returns image as string or false on failure
650          *
651          * @return mixed
652          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
653          */
654         public function asString()
655         {
656                 if (!$this->isValid()) {
657                         return false;
658                 }
659
660                 if ($this->isImagick()) {
661                         try {
662                                 /* Clean it */
663                                 $this->image = $this->image->deconstructImages();
664                                 return $this->image->getImagesBlob();
665                         } catch (Exception $e) {
666                                 return false;
667                         }
668                 }
669
670                 $stream = fopen('php://memory','r+');
671
672                 // Enable interlacing
673                 imageinterlace($this->image, true);
674
675                 switch ($this->getType()) {
676                         case 'image/png':
677                                 $quality = DI::config()->get('system', 'png_quality');
678                                 imagepng($this->image, $stream, $quality);
679                                 break;
680
681                         case 'image/jpeg':
682                         case 'image/jpg':
683                                 $quality = DI::config()->get('system', 'jpeg_quality');
684                                 imagejpeg($this->image, $stream, $quality);
685                                 break;
686                 }
687                 rewind($stream);
688                 return stream_get_contents($stream);
689         }
690
691         /**
692          * Create a blurhash out of a given image string
693          *
694          * @param string $img_str
695          * @return string
696          */
697         public function getBlurHash(): string
698         {
699                 $image = New Image($this->asString());
700                 if (empty($image) || !$this->isValid()) {
701                         return '';
702                 }
703
704                 $width  = $image->getWidth();
705                 $height = $image->getHeight();
706
707                 if (max($width, $height) > 90) {
708                         $image->scaleDown(90);
709                         $width  = $image->getWidth();
710                         $height = $image->getHeight();
711                 }
712
713                 if (empty($width) || empty($height)) {
714                         return '';
715                 }
716
717                 $pixels = [];
718                 for ($y = 0; $y < $height; ++$y) {
719                         $row = [];
720                         for ($x = 0; $x < $width; ++$x) {
721                                 if ($image->isImagick()) {
722                                         try {
723                                                 $colors = $image->image->getImagePixelColor($x, $y)->getColor();
724                                         } catch (\Exception $exception) {
725                                                 return '';
726                                         }
727                                         $row[] = [$colors['r'], $colors['g'], $colors['b']];
728                                 } else {
729                                         $index = imagecolorat($image->image, $x, $y);
730                                         $colors = @imagecolorsforindex($image->image, $index);
731                                         $row[] = [$colors['red'], $colors['green'], $colors['blue']];
732                                 }
733                         }
734                         $pixels[] = $row;
735                 }
736
737                 // The components define the amount of details (1 to 9).
738                 $components_x = 9;
739                 $components_y = 9;
740
741                 return Blurhash::encode($pixels, $components_x, $components_y);
742         }
743
744         /**
745          * Create an image out of a blurhash
746          *
747          * @param string $blurhash
748          * @param integer $width
749          * @param integer $height
750          * @return void
751          */
752         public function getFromBlurHash(string $blurhash, int $width, int $height)
753         {
754                 $scaled = Images::getScalingDimensions($width, $height, 90);
755                 $pixels = Blurhash::decode($blurhash, $scaled['width'], $scaled['height']);
756
757                 if ($this->isImagick()) {
758                         $this->image = new Imagick();
759                         $draw  = new ImagickDraw();
760                         $this->image->newImage($scaled['width'], $scaled['height'], '', 'png');
761                 } else {
762                         $this->image = imagecreatetruecolor($scaled['width'], $scaled['height']);
763                 }
764
765                 for ($y = 0; $y < $scaled['height']; ++$y) {
766                         for ($x = 0; $x < $scaled['width']; ++$x) {
767                                 [$r, $g, $b] = $pixels[$y][$x];
768                                 if ($this->isImagick()) {
769                                         $draw->setFillColor("rgb($r, $g, $b)");
770                                         $draw->point($x, $y);
771                                 } else {
772                                         imagesetpixel($this->image, $x, $y, imagecolorallocate($this->image, $r, $g, $b));
773                                 }
774                         }
775                 }
776
777                 if ($this->isImagick()) {
778                         $this->image->drawImage($draw);
779                         $this->width  = $this->image->getImageWidth();
780                         $this->height = $this->image->getImageHeight();
781                 } else {
782                         $this->width  = imagesx($this->image);
783                         $this->height = imagesy($this->image);
784                 }
785
786                 $this->valid = !empty($this->image);
787
788                 $this->scaleUp(min($width, $height));
789         }
790 }