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