]> git.mxchange.org Git - friendica.git/blob - src/Object/Image.php
Remove deprecated method to find duplicates (issue from 2013)
[friendica.git] / src / Object / Image.php
1 <?php
2 /**
3  * @file src/Object/Image.php
4  * @brief This file contains the Image class for image processing
5  */
6 namespace Friendica\Object;
7
8 use Exception;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
13 use Friendica\Util\Network;
14 use Imagick;
15 use ImagickPixel;
16
17 /**
18  * Class to handle images
19  */
20 class Image
21 {
22         /** @var Imagick|resource */
23         private $image;
24
25         /*
26          * Put back gd stuff, not everybody have Imagick
27          */
28         private $imagick;
29         private $width;
30         private $height;
31         private $valid;
32         private $type;
33         private $types;
34
35         /**
36          * @brief supported mimetypes and corresponding file extensions
37          * @return array
38          */
39         public static function supportedTypes()
40         {
41                 if (class_exists('Imagick')) {
42                         // Imagick::queryFormats won't help us a lot there...
43                         // At least, not yet, other parts of friendica uses this array
44                         $t = [
45                                 'image/jpeg' => 'jpg',
46                                 'image/png' => 'png',
47                                 'image/gif' => 'gif'
48                         ];
49                 } else {
50                         $t = [];
51                         $t['image/jpeg'] ='jpg';
52                         if (imagetypes() & IMG_PNG) {
53                                 $t['image/png'] = 'png';
54                         }
55                 }
56
57                 return $t;
58         }
59
60         /**
61          * @brief Constructor
62          * @param string  $data
63          * @param boolean $type optional, default null
64          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
65          * @throws \ImagickException
66          */
67         public function __construct($data, $type = null)
68         {
69                 $this->imagick = class_exists('Imagick');
70                 $this->types = static::supportedTypes();
71                 if (!array_key_exists($type, $this->types)) {
72                         $type='image/jpeg';
73                 }
74                 $this->type = $type;
75
76                 if ($this->isImagick() && $this->loadData($data)) {
77                         return true;
78                 } else {
79                         // Failed to load with Imagick, fallback
80                         $this->imagick = false;
81                 }
82                 return $this->loadData($data);
83         }
84
85         /**
86          * @brief Destructor
87          * @return void
88          */
89         public function __destruct()
90         {
91                 if ($this->image) {
92                         if ($this->isImagick()) {
93                                 $this->image->clear();
94                                 $this->image->destroy();
95                                 return;
96                         }
97                         if (is_resource($this->image)) {
98                                 imagedestroy($this->image);
99                         }
100                 }
101         }
102
103         /**
104          * @return boolean
105          */
106         public function isImagick()
107         {
108                 return $this->imagick;
109         }
110
111         /**
112          * @brief Maps Mime types to Imagick formats
113          * @return array With with image formats (mime type as key)
114          */
115         public static function getFormatsMap()
116         {
117                 $m = [
118                         'image/jpeg' => 'JPG',
119                         'image/png' => 'PNG',
120                         'image/gif' => 'GIF'
121                 ];
122                 return $m;
123         }
124
125         /**
126          * @param string $data data
127          * @return boolean
128          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129          * @throws \ImagickException
130          */
131         private function loadData($data)
132         {
133                 if ($this->isImagick()) {
134                         $this->image = new Imagick();
135                         try {
136                                 $this->image->readImageBlob($data);
137                         } catch (Exception $e) {
138                                 // Imagick couldn't use the data
139                                 return false;
140                         }
141
142                         /*
143                          * Setup the image to the format it will be saved to
144                          */
145                         $map = self::getFormatsMap();
146                         $format = $map[$this->type];
147                         $this->image->setFormat($format);
148
149                         // Always coalesce, if it is not a multi-frame image it won't hurt anyway
150                         $this->image = $this->image->coalesceImages();
151
152                         /*
153                          * setup the compression here, so we'll do it only once
154                          */
155                         switch ($this->getType()) {
156                                 case "image/png":
157                                         $quality = Config::get('system', 'png_quality');
158                                         if ((! $quality) || ($quality > 9)) {
159                                                 $quality = PNG_QUALITY;
160                                         }
161                                         /*
162                                          * From http://www.imagemagick.org/script/command-line-options.php#quality:
163                                          *
164                                          * 'For the MNG and PNG image formats, the quality value sets
165                                          * the zlib compression level (quality / 10) and filter-type (quality % 10).
166                                          * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
167                                          * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
168                                          */
169                                         $quality = $quality * 10;
170                                         $this->image->setCompressionQuality($quality);
171                                         break;
172                                 case "image/jpeg":
173                                         $quality = Config::get('system', 'jpeg_quality');
174                                         if ((! $quality) || ($quality > 100)) {
175                                                 $quality = JPEG_QUALITY;
176                                         }
177                                         $this->image->setCompressionQuality($quality);
178                         }
179
180                         // The 'width' and 'height' properties are only used by non-Imagick routines.
181                         $this->width  = $this->image->getImageWidth();
182                         $this->height = $this->image->getImageHeight();
183                         $this->valid  = true;
184
185                         return true;
186                 }
187
188                 $this->valid = false;
189                 $this->image = @imagecreatefromstring($data);
190                 if ($this->image !== false) {
191                         $this->width  = imagesx($this->image);
192                         $this->height = imagesy($this->image);
193                         $this->valid  = true;
194                         imagealphablending($this->image, false);
195                         imagesavealpha($this->image, true);
196
197                         return true;
198                 }
199
200                 return false;
201         }
202
203         /**
204          * @return boolean
205          */
206         public function isValid()
207         {
208                 if ($this->isImagick()) {
209                         return ($this->image !== false);
210                 }
211                 return $this->valid;
212         }
213
214         /**
215          * @return mixed
216          */
217         public function getWidth()
218         {
219                 if (!$this->isValid()) {
220                         return false;
221                 }
222
223                 if ($this->isImagick()) {
224                         return $this->image->getImageWidth();
225                 }
226                 return $this->width;
227         }
228
229         /**
230          * @return mixed
231          */
232         public function getHeight()
233         {
234                 if (!$this->isValid()) {
235                         return false;
236                 }
237
238                 if ($this->isImagick()) {
239                         return $this->image->getImageHeight();
240                 }
241                 return $this->height;
242         }
243
244         /**
245          * @return mixed
246          */
247         public function getImage()
248         {
249                 if (!$this->isValid()) {
250                         return false;
251                 }
252
253                 if ($this->isImagick()) {
254                         /* Clean it */
255                         $this->image = $this->image->deconstructImages();
256                         return $this->image;
257                 }
258                 return $this->image;
259         }
260
261         /**
262          * @return mixed
263          */
264         public function getType()
265         {
266                 if (!$this->isValid()) {
267                         return false;
268                 }
269
270                 return $this->type;
271         }
272
273         /**
274          * @return mixed
275          */
276         public function getExt()
277         {
278                 if (!$this->isValid()) {
279                         return false;
280                 }
281
282                 return $this->types[$this->getType()];
283         }
284
285         /**
286          * @param integer $max max dimension
287          * @return mixed
288          */
289         public function scaleDown($max)
290         {
291                 if (!$this->isValid()) {
292                         return false;
293                 }
294
295                 $width = $this->getWidth();
296                 $height = $this->getHeight();
297
298                 if ((! $width)|| (! $height)) {
299                         return false;
300                 }
301
302                 if ($width > $max && $height > $max) {
303                         // very tall image (greater than 16:9)
304                         // constrain the width - let the height float.
305
306                         if ((($height * 9) / 16) > $width) {
307                                 $dest_width = $max;
308                                 $dest_height = intval(($height * $max) / $width);
309                         } elseif ($width > $height) {
310                                 // else constrain both dimensions
311                                 $dest_width = $max;
312                                 $dest_height = intval(($height * $max) / $width);
313                         } else {
314                                 $dest_width = intval(($width * $max) / $height);
315                                 $dest_height = $max;
316                         }
317                 } else {
318                         if ($width > $max) {
319                                 $dest_width = $max;
320                                 $dest_height = intval(($height * $max) / $width);
321                         } else {
322                                 if ($height > $max) {
323                                         // very tall image (greater than 16:9)
324                                         // but width is OK - don't do anything
325
326                                         if ((($height * 9) / 16) > $width) {
327                                                 $dest_width = $width;
328                                                 $dest_height = $height;
329                                         } else {
330                                                 $dest_width = intval(($width * $max) / $height);
331                                                 $dest_height = $max;
332                                         }
333                                 } else {
334                                         $dest_width = $width;
335                                         $dest_height = $height;
336                                 }
337                         }
338                 }
339
340                 return $this->scale($dest_width, $dest_height);
341         }
342
343         /**
344          * @param integer $degrees degrees to rotate image
345          * @return mixed
346          */
347         public function rotate($degrees)
348         {
349                 if (!$this->isValid()) {
350                         return false;
351                 }
352
353                 if ($this->isImagick()) {
354                         $this->image->setFirstIterator();
355                         do {
356                                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
357                         } while ($this->image->nextImage());
358                         return;
359                 }
360
361                 // if script dies at this point check memory_limit setting in php.ini
362                 $this->image  = imagerotate($this->image, $degrees, 0);
363                 $this->width  = imagesx($this->image);
364                 $this->height = imagesy($this->image);
365         }
366
367         /**
368          * @param boolean $horiz optional, default true
369          * @param boolean $vert  optional, default false
370          * @return mixed
371          */
372         public function flip($horiz = true, $vert = false)
373         {
374                 if (!$this->isValid()) {
375                         return false;
376                 }
377
378                 if ($this->isImagick()) {
379                         $this->image->setFirstIterator();
380                         do {
381                                 if ($horiz) {
382                                         $this->image->flipImage();
383                                 }
384                                 if ($vert) {
385                                         $this->image->flopImage();
386                                 }
387                         } while ($this->image->nextImage());
388                         return;
389                 }
390
391                 $w = imagesx($this->image);
392                 $h = imagesy($this->image);
393                 $flipped = imagecreate($w, $h);
394                 if ($horiz) {
395                         for ($x = 0; $x < $w; $x++) {
396                                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
397                         }
398                 }
399                 if ($vert) {
400                         for ($y = 0; $y < $h; $y++) {
401                                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
402                         }
403                 }
404                 $this->image = $flipped;
405         }
406
407         /**
408          * @param string $filename filename
409          * @return mixed
410          */
411         public function orient($filename)
412         {
413                 if ($this->isImagick()) {
414                         // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
415                         $orientation = $this->image->getImageOrientation();
416                         switch ($orientation) {
417                                 case Imagick::ORIENTATION_BOTTOMRIGHT:
418                                         $this->image->rotateimage("#000", 180);
419                                         break;
420                                 case Imagick::ORIENTATION_RIGHTTOP:
421                                         $this->image->rotateimage("#000", 90);
422                                         break;
423                                 case Imagick::ORIENTATION_LEFTBOTTOM:
424                                         $this->image->rotateimage("#000", -90);
425                                         break;
426                         }
427
428                         $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
429                         return true;
430                 }
431                 // based off comment on http://php.net/manual/en/function.imagerotate.php
432
433                 if (!$this->isValid()) {
434                         return false;
435                 }
436
437                 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
438                         return;
439                 }
440
441                 $exif = @exif_read_data($filename, null, true);
442                 if (!$exif) {
443                         return;
444                 }
445
446                 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
447
448                 switch ($ort) {
449                         case 1: // nothing
450                                 break;
451
452                         case 2: // horizontal flip
453                                 $this->flip();
454                                 break;
455
456                         case 3: // 180 rotate left
457                                 $this->rotate(180);
458                                 break;
459
460                         case 4: // vertical flip
461                                 $this->flip(false, true);
462                                 break;
463
464                         case 5: // vertical flip + 90 rotate right
465                                 $this->flip(false, true);
466                                 $this->rotate(-90);
467                                 break;
468
469                         case 6: // 90 rotate right
470                                 $this->rotate(-90);
471                                 break;
472
473                         case 7: // horizontal flip + 90 rotate right
474                                 $this->flip();
475                                 $this->rotate(-90);
476                                 break;
477
478                         case 8: // 90 rotate left
479                                 $this->rotate(90);
480                                 break;
481                 }
482
483                 //      Logger::log('exif: ' . print_r($exif,true));
484                 return $exif;
485         }
486
487         /**
488          * @param integer $min minimum dimension
489          * @return mixed
490          */
491         public function scaleUp($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          * @param integer $dim dimension
532          * @return mixed
533          */
534         public function scaleToSquare($dim)
535         {
536                 if (!$this->isValid()) {
537                         return false;
538                 }
539
540                 return $this->scale($dim, $dim);
541         }
542
543         /**
544          * @brief Scale image to target dimensions
545          *
546          * @param int $dest_width
547          * @param int $dest_height
548          * @return boolean
549          */
550         private function scale($dest_width, $dest_height)
551         {
552                 if (!$this->isValid()) {
553                         return false;
554                 }
555
556                 if ($this->isImagick()) {
557                         /*
558                          * If it is not animated, there will be only one iteration here,
559                          * so don't bother checking
560                          */
561                         // Don't forget to go back to the first frame
562                         $this->image->setFirstIterator();
563                         do {
564                                 // FIXME - implement horizontal bias for scaling as in following GD functions
565                                 // to allow very tall images to be constrained only horizontally.
566                                 $this->image->scaleImage($dest_width, $dest_height);
567                         } while ($this->image->nextImage());
568
569                         // These may not be necessary anymore
570                         $this->width  = $this->image->getImageWidth();
571                         $this->height = $this->image->getImageHeight();
572                 } else {
573                         $dest = imagecreatetruecolor($dest_width, $dest_height);
574                         imagealphablending($dest, false);
575                         imagesavealpha($dest, true);
576
577                         if ($this->type=='image/png') {
578                                 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
579                         }
580
581                         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
582
583                         if ($this->image) {
584                                 imagedestroy($this->image);
585                         }
586
587                         $this->image = $dest;
588                         $this->width  = imagesx($this->image);
589                         $this->height = imagesy($this->image);
590                 }
591
592                 return true;
593         }
594
595         /**
596          * @param integer $max maximum
597          * @param integer $x   x coordinate
598          * @param integer $y   y coordinate
599          * @param integer $w   width
600          * @param integer $h   height
601          * @return mixed
602          */
603         public function crop($max, $x, $y, $w, $h)
604         {
605                 if (!$this->isValid()) {
606                         return false;
607                 }
608
609                 if ($this->isImagick()) {
610                         $this->image->setFirstIterator();
611                         do {
612                                 $this->image->cropImage($w, $h, $x, $y);
613                                 /*
614                                  * We need to remove the canva,
615                                  * or the image is not resized to the crop:
616                                  * http://php.net/manual/en/imagick.cropimage.php#97232
617                                  */
618                                 $this->image->setImagePage(0, 0, 0, 0);
619                         } while ($this->image->nextImage());
620                         return $this->scaleDown($max);
621                 }
622
623                 $dest = imagecreatetruecolor($max, $max);
624                 imagealphablending($dest, false);
625                 imagesavealpha($dest, true);
626                 if ($this->type=='image/png') {
627                         imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
628                 }
629                 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
630                 if ($this->image) {
631                         imagedestroy($this->image);
632                 }
633                 $this->image = $dest;
634                 $this->width  = imagesx($this->image);
635                 $this->height = imagesy($this->image);
636         }
637
638         /**
639          * @param string $path file path
640          * @return mixed
641          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
642          */
643         public function saveToFilePath($path)
644         {
645                 if (!$this->isValid()) {
646                         return false;
647                 }
648
649                 $string = $this->asString();
650
651                 $a = \get_app();
652
653                 $stamp1 = microtime(true);
654                 file_put_contents($path, $string);
655                 $a->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
656         }
657
658         /**
659          * @brief Magic method allowing string casting of an Image object
660          *
661          * Ex: $data = $Image->asString();
662          * can be replaced by
663          * $data = (string) $Image;
664          *
665          * @return string
666          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
667          */
668         public function __toString() {
669                 return $this->asString();
670         }
671
672         /**
673          * @return mixed
674          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675          */
676         public function asString()
677         {
678                 if (!$this->isValid()) {
679                         return false;
680                 }
681
682                 if ($this->isImagick()) {
683                         /* Clean it */
684                         $this->image = $this->image->deconstructImages();
685                         $string = $this->image->getImagesBlob();
686                         return $string;
687                 }
688
689                 ob_start();
690
691                 // Enable interlacing
692                 imageinterlace($this->image, true);
693
694                 switch ($this->getType()) {
695                         case "image/png":
696                                 $quality = Config::get('system', 'png_quality');
697                                 if ((!$quality) || ($quality > 9)) {
698                                         $quality = PNG_QUALITY;
699                                 }
700                                 imagepng($this->image, null, $quality);
701                                 break;
702                         case "image/jpeg":
703                                 $quality = Config::get('system', 'jpeg_quality');
704                                 if ((!$quality) || ($quality > 100)) {
705                                         $quality = JPEG_QUALITY;
706                                 }
707                                 imagejpeg($this->image, null, $quality);
708                 }
709                 $string = ob_get_contents();
710                 ob_end_clean();
711
712                 return $string;
713         }
714
715         /**
716          * Guess image mimetype from filename or from Content-Type header
717          *
718          * @param string  $filename Image filename
719          * @param boolean $fromcurl Check Content-Type header from curl request
720          * @param string  $header   passed headers to take into account
721          *
722          * @return object
723          * @throws \ImagickException
724          */
725         public static function guessType($filename, $fromcurl = false, $header = '')
726         {
727                 Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
728                 $type = null;
729                 if ($fromcurl) {
730                         $headers=[];
731                         $h = explode("\n", $header);
732                         foreach ($h as $l) {
733                                 $data = array_map("trim", explode(":", trim($l), 2));
734                                 if (count($data) > 1) {
735                                         list($k,$v) = $data;
736                                         $headers[$k] = $v;
737                                 }
738                         }
739                         if (array_key_exists('Content-Type', $headers))
740                                 $type = $headers['Content-Type'];
741                 }
742                 if (is_null($type)) {
743                         // Guessing from extension? Isn't that... dangerous?
744                         if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
745                                 /**
746                                  * Well, this not much better,
747                                  * but at least it comes from the data inside the image,
748                                  * we won't be tricked by a manipulated extension
749                                  */
750                                 $image = new Imagick($filename);
751                                 $type = $image->getImageMimeType();
752                                 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
753                         } else {
754                                 $ext = pathinfo($filename, PATHINFO_EXTENSION);
755                                 $types = self::supportedTypes();
756                                 $type = "image/jpeg";
757                                 foreach ($types as $m => $e) {
758                                         if ($ext == $e) {
759                                                 $type = $m;
760                                         }
761                                 }
762                         }
763                 }
764                 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
765                 return $type;
766         }
767
768         /**
769          * @param string $url url
770          * @return object
771          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
772          */
773         public static function getInfoFromURL($url)
774         {
775                 $data = [];
776
777                 if (empty($url)) {
778                         return $data;
779                 }
780
781                 $data = Cache::get($url);
782
783                 if (is_null($data) || !$data || !is_array($data)) {
784                         $img_str = Network::fetchUrl($url, true, 4);
785
786                         if (!$img_str) {
787                                 return false;
788                         }
789
790                         $filesize = strlen($img_str);
791
792                         try {
793                                 if (function_exists("getimagesizefromstring")) {
794                                         $data = @getimagesizefromstring($img_str);
795                                 } else {
796                                         $tempfile = tempnam(get_temppath(), "cache");
797
798                                         $a = \get_app();
799                                         $stamp1 = microtime(true);
800                                         file_put_contents($tempfile, $img_str);
801                                         $a->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
802
803                                         $data = getimagesize($tempfile);
804                                         unlink($tempfile);
805                                 }
806                         } catch (Exception $e) {
807                                 return false;
808                         }
809
810                         if ($data) {
811                                 $data["size"] = $filesize;
812                         }
813
814                         Cache::set($url, $data);
815                 }
816
817                 return $data;
818         }
819
820         /**
821          * @param integer $width  width
822          * @param integer $height height
823          * @param integer $max    max
824          * @return array
825          */
826         public static function getScalingDimensions($width, $height, $max)
827         {
828                 if ((!$width) || (!$height)) {
829                         return false;
830                 }
831
832                 if ($width > $max && $height > $max) {
833                         // very tall image (greater than 16:9)
834                         // constrain the width - let the height float.
835
836                         if ((($height * 9) / 16) > $width) {
837                                 $dest_width = $max;
838                                 $dest_height = intval(($height * $max) / $width);
839                         } elseif ($width > $height) {
840                                 // else constrain both dimensions
841                                 $dest_width = $max;
842                                 $dest_height = intval(($height * $max) / $width);
843                         } else {
844                                 $dest_width = intval(($width * $max) / $height);
845                                 $dest_height = $max;
846                         }
847                 } else {
848                         if ($width > $max) {
849                                 $dest_width = $max;
850                                 $dest_height = intval(($height * $max) / $width);
851                         } else {
852                                 if ($height > $max) {
853                                         // very tall image (greater than 16:9)
854                                         // but width is OK - don't do anything
855
856                                         if ((($height * 9) / 16) > $width) {
857                                                 $dest_width = $width;
858                                                 $dest_height = $height;
859                                         } else {
860                                                 $dest_width = intval(($width * $max) / $height);
861                                                 $dest_height = $max;
862                                         }
863                                 } else {
864                                         $dest_width = $width;
865                                         $dest_height = $height;
866                                 }
867                         }
868                 }
869                 return ["width" => $dest_width, "height" => $dest_height];
870         }
871 }