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