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