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