]> git.mxchange.org Git - friendica.git/blob - src/Object/Image.php
1d2832f20a9a075ab6f2df3b8c08395eedd60866
[friendica.git] / src / Object / Image.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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
179                                 return true;
180                         }
181                 } catch (\Throwable $error) {
182                         /** @see https://github.com/php/doc-en/commit/d09a881a8e9059d11e756ee59d75bf404d6941ed */
183                         if (strstr($error->getMessage(), "gd-webp cannot allocate temporary buffer")) {
184                                 DI::logger()->notice('Image is probably animated and therefore unsupported', ['error' => $error]);
185                         } else {
186                                 DI::logger()->warning('Unexpected throwable.', ['error' => $error]);
187                         }
188                 }
189
190                 return false;
191         }
192
193         /**
194          * @return boolean
195          */
196         public function isValid(): bool
197         {
198                 if ($this->isImagick()) {
199                         return ($this->image !== false);
200                 }
201                 return $this->valid;
202         }
203
204         /**
205          * @return mixed
206          */
207         public function getWidth()
208         {
209                 if (!$this->isValid()) {
210                         return false;
211                 }
212
213                 return $this->width;
214         }
215
216         /**
217          * @return mixed
218          */
219         public function getHeight()
220         {
221                 if (!$this->isValid()) {
222                         return false;
223                 }
224
225                 return $this->height;
226         }
227
228         /**
229          * @return mixed
230          */
231         public function getImage()
232         {
233                 if (!$this->isValid()) {
234                         return false;
235                 }
236
237                 if ($this->isImagick()) {
238                         try {
239                                 /* Clean it */
240                                 $this->image = $this->image->deconstructImages();
241                                 return $this->image;
242                         } catch (Exception $e) {
243                                 return false;
244                         }
245                 }
246                 return $this->image;
247         }
248
249         /**
250          * @return mixed
251          */
252         public function getType()
253         {
254                 if (!$this->isValid()) {
255                         return false;
256                 }
257
258                 return $this->type;
259         }
260
261         /**
262          * @return mixed
263          */
264         public function getExt()
265         {
266                 if (!$this->isValid()) {
267                         return false;
268                 }
269
270                 return $this->types[$this->getType()];
271         }
272
273         /**
274          * Scales image down
275          *
276          * @param integer $max max dimension
277          * @return mixed
278          */
279         public function scaleDown(int $max)
280         {
281                 if (!$this->isValid()) {
282                         return false;
283                 }
284
285                 $width = $this->getWidth();
286                 $height = $this->getHeight();
287
288                 if ((! $width)|| (! $height)) {
289                         return false;
290                 }
291
292                 if ($width > $max && $height > $max) {
293                         // very tall image (greater than 16:9)
294                         // constrain the width - let the height float.
295
296                         if ((($height * 9) / 16) > $width) {
297                                 $dest_width = $max;
298                                 $dest_height = intval(($height * $max) / $width);
299                         } elseif ($width > $height) {
300                                 // else constrain both dimensions
301                                 $dest_width = $max;
302                                 $dest_height = intval(($height * $max) / $width);
303                         } else {
304                                 $dest_width = intval(($width * $max) / $height);
305                                 $dest_height = $max;
306                         }
307                 } else {
308                         if ($width > $max) {
309                                 $dest_width = $max;
310                                 $dest_height = intval(($height * $max) / $width);
311                         } else {
312                                 if ($height > $max) {
313                                         // very tall image (greater than 16:9)
314                                         // but width is OK - don't do anything
315
316                                         if ((($height * 9) / 16) > $width) {
317                                                 $dest_width = $width;
318                                                 $dest_height = $height;
319                                         } else {
320                                                 $dest_width = intval(($width * $max) / $height);
321                                                 $dest_height = $max;
322                                         }
323                                 } else {
324                                         $dest_width = $width;
325                                         $dest_height = $height;
326                                 }
327                         }
328                 }
329
330                 return $this->scale($dest_width, $dest_height);
331         }
332
333         /**
334          * Rotates image
335          *
336          * @param integer $degrees degrees to rotate image
337          * @return mixed
338          */
339         public function rotate(int $degrees)
340         {
341                 if (!$this->isValid()) {
342                         return false;
343                 }
344
345                 if ($this->isImagick()) {
346                         $this->image->setFirstIterator();
347                         do {
348                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
349                         } while ($this->image->nextImage());
350
351                         $this->width  = $this->image->getImageWidth();
352                         $this->height = $this->image->getImageHeight();
353                         return;
354                 }
355
356                 // if script dies at this point check memory_limit setting in php.ini
357                 $this->image  = imagerotate($this->image, $degrees, 0);
358                 $this->width  = imagesx($this->image);
359                 $this->height = imagesy($this->image);
360         }
361
362         /**
363          * Flips image
364          *
365          * @param boolean $horiz optional, default true
366          * @param boolean $vert  optional, default false
367          * @return mixed
368          */
369         public function flip(bool $horiz = true, bool $vert = false)
370         {
371                 if (!$this->isValid()) {
372                         return false;
373                 }
374
375                 if ($this->isImagick()) {
376                         $this->image->setFirstIterator();
377                         do {
378                                 if ($horiz) {
379                                         $this->image->flipImage();
380                                 }
381                                 if ($vert) {
382                                         $this->image->flopImage();
383                                 }
384                         } while ($this->image->nextImage());
385                         return;
386                 }
387
388                 $w = imagesx($this->image);
389                 $h = imagesy($this->image);
390                 $flipped = imagecreate($w, $h);
391                 if ($horiz) {
392                         for ($x = 0; $x < $w; $x++) {
393                                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
394                         }
395                 }
396                 if ($vert) {
397                         for ($y = 0; $y < $h; $y++) {
398                                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
399                         }
400                 }
401                 $this->image = $flipped;
402         }
403
404         /**
405          * Fixes orientation and maybe returns EXIF data (?)
406          *
407          * @param string $filename Filename
408          * @return mixed
409          */
410         public function orient(string $filename)
411         {
412                 if ($this->isImagick()) {
413                         // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
414                         $orientation = $this->image->getImageOrientation();
415                         switch ($orientation) {
416                                 case Imagick::ORIENTATION_BOTTOMRIGHT:
417                                         $this->image->rotateimage("#000", 180);
418                                         break;
419                                 case Imagick::ORIENTATION_RIGHTTOP:
420                                         $this->image->rotateimage("#000", 90);
421                                         break;
422                                 case Imagick::ORIENTATION_LEFTBOTTOM:
423                                         $this->image->rotateimage("#000", -90);
424                                         break;
425                         }
426
427                         $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
428                         return true;
429                 }
430                 // based off comment on http://php.net/manual/en/function.imagerotate.php
431
432                 if (!$this->isValid()) {
433                         return false;
434                 }
435
436                 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
437                         return;
438                 }
439
440                 $exif = @exif_read_data($filename, null, true);
441                 if (!$exif) {
442                         return;
443                 }
444
445                 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
446
447                 switch ($ort) {
448                         case 1: // nothing
449                                 break;
450
451                         case 2: // horizontal flip
452                                 $this->flip();
453                                 break;
454
455                         case 3: // 180 rotate left
456                                 $this->rotate(180);
457                                 break;
458
459                         case 4: // vertical flip
460                                 $this->flip(false, true);
461                                 break;
462
463                         case 5: // vertical flip + 90 rotate right
464                                 $this->flip(false, true);
465                                 $this->rotate(-90);
466                                 break;
467
468                         case 6: // 90 rotate right
469                                 $this->rotate(-90);
470                                 break;
471
472                         case 7: // horizontal flip + 90 rotate right
473                                 $this->flip();
474                                 $this->rotate(-90);
475                                 break;
476
477                         case 8: // 90 rotate left
478                                 $this->rotate(90);
479                                 break;
480                 }
481
482                 return $exif;
483         }
484
485         /**
486          * Rescales image to minimum size
487          *
488          * @param integer $min Minimum dimension
489          * @return mixed
490          */
491         public function scaleUp(int $min)
492         {
493                 if (!$this->isValid()) {
494                         return false;
495                 }
496
497                 $width = $this->getWidth();
498                 $height = $this->getHeight();
499
500                 if ((!$width)|| (!$height)) {
501                         return false;
502                 }
503
504                 if ($width < $min && $height < $min) {
505                         if ($width > $height) {
506                                 $dest_width = $min;
507                                 $dest_height = intval(($height * $min) / $width);
508                         } else {
509                                 $dest_width = intval(($width * $min) / $height);
510                                 $dest_height = $min;
511                         }
512                 } else {
513                         if ($width < $min) {
514                                 $dest_width = $min;
515                                 $dest_height = intval(($height * $min) / $width);
516                         } else {
517                                 if ($height < $min) {
518                                         $dest_width = intval(($width * $min) / $height);
519                                         $dest_height = $min;
520                                 } else {
521                                         $dest_width = $width;
522                                         $dest_height = $height;
523                                 }
524                         }
525                 }
526
527                 return $this->scale($dest_width, $dest_height);
528         }
529
530         /**
531          * Scales image to square
532          *
533          * @param integer $dim Dimension
534          * @return mixed
535          */
536         public function scaleToSquare(int $dim)
537         {
538                 if (!$this->isValid()) {
539                         return false;
540                 }
541
542                 return $this->scale($dim, $dim);
543         }
544
545         /**
546          * Scale image to target dimensions
547          *
548          * @param int $dest_width Destination width
549          * @param int $dest_height Destination height
550          * @return boolean Success
551          */
552         private function scale(int $dest_width, int $dest_height): bool
553         {
554                 if (!$this->isValid()) {
555                         return false;
556                 }
557
558                 if ($this->isImagick()) {
559                         /*
560                          * If it is not animated, there will be only one iteration here,
561                          * so don't bother checking
562                          */
563                         // Don't forget to go back to the first frame
564                         $this->image->setFirstIterator();
565                         do {
566                                 // FIXME - implement horizontal bias for scaling as in following GD functions
567                                 // to allow very tall images to be constrained only horizontally.
568                                 try {
569                                         $this->image->scaleImage($dest_width, $dest_height);
570                                 } catch (Exception $e) {
571                                         // Imagick couldn't use the data
572                                         return false;
573                                 }
574                         } while ($this->image->nextImage());
575
576                         $this->width  = $this->image->getImageWidth();
577                         $this->height = $this->image->getImageHeight();
578                 } else {
579                         $dest = imagecreatetruecolor($dest_width, $dest_height);
580                         imagealphablending($dest, false);
581                         imagesavealpha($dest, true);
582
583                         if ($this->type=='image/png') {
584                                 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
585                         }
586
587                         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
588
589                         if ($this->image) {
590                                 imagedestroy($this->image);
591                         }
592
593                         $this->image = $dest;
594                         $this->width  = imagesx($this->image);
595                         $this->height = imagesy($this->image);
596                 }
597
598                 return true;
599         }
600
601         /**
602          * Convert a GIF to a PNG to make it static
603          *
604          * @return void
605          */
606         public function toStatic()
607         {
608                 if ($this->type != 'image/gif') {
609                         return;
610                 }
611
612                 if ($this->isImagick()) {
613                         $this->type == 'image/png';
614                         $this->image->setFormat('png');
615                 }
616         }
617
618         /**
619          * Crops image
620          *
621          * @param integer $max maximum
622          * @param integer $x   x coordinate
623          * @param integer $y   y coordinate
624          * @param integer $w   width
625          * @param integer $h   height
626          * @return mixed
627          */
628         public function crop(int $max, int $x, int $y, int $w, int $h)
629         {
630                 if (!$this->isValid()) {
631                         return false;
632                 }
633
634                 if ($this->isImagick()) {
635                         $this->image->setFirstIterator();
636                         do {
637                                 $this->image->cropImage($w, $h, $x, $y);
638                                 /*
639                                  * We need to remove the canva,
640                                  * or the image is not resized to the crop:
641                                  * http://php.net/manual/en/imagick.cropimage.php#97232
642                                  */
643                                 $this->image->setImagePage(0, 0, 0, 0);
644                         } while ($this->image->nextImage());
645                         return $this->scaleDown($max);
646                 }
647
648                 $dest = imagecreatetruecolor($max, $max);
649                 imagealphablending($dest, false);
650                 imagesavealpha($dest, true);
651                 if ($this->type=='image/png') {
652                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
653                 }
654                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
655                 if ($this->image) {
656                         imagedestroy($this->image);
657                 }
658                 $this->image  = $dest;
659                 $this->width  = imagesx($this->image);
660                 $this->height = imagesy($this->image);
661
662                 // All successful
663                 return true;
664         }
665
666         /**
667          * Magic method allowing string casting of an Image object
668          *
669          * Ex: $data = $Image->asString();
670          * can be replaced by
671          * $data = (string) $Image;
672          *
673          * @return string
674          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675          */
676         public function __toString(): string
677         {
678                 return (string) $this->asString();
679         }
680
681         /**
682          * Returns image as string or false on failure
683          *
684          * @return mixed
685          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
686          */
687         public function asString()
688         {
689                 if (!$this->isValid()) {
690                         return false;
691                 }
692
693                 if ($this->isImagick()) {
694                         try {
695                                 /* Clean it */
696                                 $this->image = $this->image->deconstructImages();
697                                 return $this->image->getImagesBlob();
698                         } catch (Exception $e) {
699                                 return false;
700                         }
701                 }
702
703                 $stream = fopen('php://memory','r+');
704
705                 // Enable interlacing
706                 imageinterlace($this->image, true);
707
708                 switch ($this->getType()) {
709                         case 'image/png':
710                                 $quality = DI::config()->get('system', 'png_quality');
711                                 imagepng($this->image, $stream, $quality);
712                                 break;
713
714                         case 'image/jpeg':
715                         case 'image/jpg':
716                                 $quality = DI::config()->get('system', 'jpeg_quality');
717                                 imagejpeg($this->image, $stream, $quality);
718                                 break;
719                 }
720                 rewind($stream);
721                 return stream_get_contents($stream);
722         }
723
724         /**
725          * Create a blurhash out of a given image string
726          *
727          * @param string $img_str
728          * @return string
729          */
730         public function getBlurHash(): string
731         {
732                 $image = New Image($this->asString());
733                 if (empty($image) || !$this->isValid()) {
734                         return '';
735                 }
736
737                 $width  = $image->getWidth();
738                 $height = $image->getHeight();
739
740                 if (max($width, $height) > 90) {
741                         $image->scaleDown(90);
742                         $width  = $image->getWidth();
743                         $height = $image->getHeight();
744                 }
745
746                 if (empty($width) || empty($height)) {
747                         return '';
748                 }
749
750                 $pixels = [];
751                 for ($y = 0; $y < $height; ++$y) {
752                         $row = [];
753                         for ($x = 0; $x < $width; ++$x) {
754                                 if ($image->isImagick()) {
755                                         try {
756                                                 $colors = $image->image->getImagePixelColor($x, $y)->getColor();
757                                         } catch (\Throwable $th) {
758                                                 return '';
759                                         }
760                                         $row[] = [$colors['r'], $colors['g'], $colors['b']];
761                                 } else {
762                                         $index = imagecolorat($image->image, $x, $y);
763                                         $colors = @imagecolorsforindex($image->image, $index);
764                                         $row[] = [$colors['red'], $colors['green'], $colors['blue']];
765                                 }
766                         }
767                         $pixels[] = $row;
768                 }
769
770                 // The components define the amount of details (1 to 9).
771                 $components_x = 9;
772                 $components_y = 9;
773
774                 return Blurhash::encode($pixels, $components_x, $components_y);
775         }
776
777         /**
778          * Create an image out of a blurhash
779          *
780          * @param string $blurhash
781          * @param integer $width
782          * @param integer $height
783          * @return void
784          */
785         public function getFromBlurHash(string $blurhash, int $width, int $height)
786         {
787                 $scaled = Images::getScalingDimensions($width, $height, 90);
788                 $pixels = Blurhash::decode($blurhash, $scaled['width'], $scaled['height']);
789
790                 if ($this->isImagick()) {
791                         $this->image = new Imagick();
792                         $draw  = new ImagickDraw();
793                         $this->image->newImage($scaled['width'], $scaled['height'], '', 'png');
794                 } else {
795                         $this->image = imagecreatetruecolor($scaled['width'], $scaled['height']);
796                 }
797
798                 for ($y = 0; $y < $scaled['height']; ++$y) {
799                         for ($x = 0; $x < $scaled['width']; ++$x) {
800                                 [$r, $g, $b] = $pixels[$y][$x];
801                                 if ($this->isImagick()) {
802                                         $draw->setFillColor("rgb($r, $g, $b)");
803                                         $draw->point($x, $y);
804                                 } else {
805                                         imagesetpixel($this->image, $x, $y, imagecolorallocate($this->image, $r, $g, $b));
806                                 }
807                         }
808                 }
809
810                 if ($this->isImagick()) {
811                         $this->image->drawImage($draw);
812                         $this->width  = $this->image->getImageWidth();
813                         $this->height = $this->image->getImageHeight();
814                 } else {
815                         $this->width  = imagesx($this->image);
816                         $this->height = imagesy($this->image);
817                 }
818
819                 $this->valid = !empty($this->image);
820
821                 $this->scaleUp(min($width, $height));
822         }
823 }