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