]> git.mxchange.org Git - friendica.git/blob - include/Photo.php
slight adjustment to Photo scaling - also discovered imagick resize may need some...
[friendica.git] / include / Photo.php
1 <?php
2
3 if(! class_exists("Photo")) {
4 class Photo {
5
6     private $image;
7
8     /**
9      * Put back gd stuff, not everybody have Imagick
10      */
11     private $imagick;
12     private $width;
13     private $height;
14     private $valid;
15     private $type;
16     private $types;
17
18     /**
19      * supported mimetypes and corresponding file extensions
20      */
21     static function supportedTypes() {
22         if(class_exists('Imagick')) {
23             /**
24              * Imagick::queryFormats won't help us a lot there...
25              * At least, not yet, other parts of friendica uses this array
26              */
27             $t = array(
28                 'image/jpeg' => 'jpg',
29                 'image/png' => 'png',
30                 'image/gif' => 'gif'
31             );
32         } else {
33             $t = array();
34             $t['image/jpeg'] ='jpg';
35             if (imagetypes() & IMG_PNG) $t['image/png'] = 'png';
36         }
37
38         return $t;
39     }
40
41     public function __construct($data, $type=null) {
42         $this->imagick = class_exists('Imagick');
43         $this->types = $this->supportedTypes();
44         if (!array_key_exists($type,$this->types)){
45             $type='image/jpeg';
46         }
47         $this->type = $type;
48
49         if($this->is_imagick() && $this->load_data($data)) {
50                         return true;
51                 } else {
52                         // Failed to load with Imagick, fallback
53                         $this->imagick = false;
54                 }
55                 return $this->load_data($data);
56     }
57
58     public function __destruct() {
59         if($this->image) {
60             if($this->is_imagick()) {
61                 $this->image->clear();
62                 $this->image->destroy();
63                 return;
64             }
65             imagedestroy($this->image);
66         }
67     }
68
69     public function is_imagick() {
70         return $this->imagick;
71     }
72
73     /**
74      * Maps Mime types to Imagick formats
75      */
76     public function get_FormatsMap() {
77         $m = array(
78             'image/jpeg' => 'JPG',
79             'image/png' => 'PNG',
80             'image/gif' => 'GIF'
81         );
82         return $m;
83     }
84
85     private function load_data($data) {
86                 if($this->is_imagick()) {
87                         $this->image = new Imagick();
88             try {
89                                 $this->image->readImageBlob($data);
90                         }
91                         catch (Exception $e) {
92                                 // Imagick couldn't use the data
93                                 return false;
94                         }
95
96             /**
97              * Setup the image to the format it will be saved to
98              */
99             $map = $this->get_FormatsMap();
100             $format = $map[$type];
101             $this->image->setFormat($format);
102
103             // Always coalesce, if it is not a multi-frame image it won't hurt anyway
104             $this->image = $this->image->coalesceImages();
105
106             /**
107              * setup the compression here, so we'll do it only once
108              */
109             switch($this->getType()){
110                 case "image/png":
111                     $quality = get_config('system','png_quality');
112                     if((! $quality) || ($quality > 9))
113                         $quality = PNG_QUALITY;
114                     /**
115                      * From http://www.imagemagick.org/script/command-line-options.php#quality:
116                      *
117                      * 'For the MNG and PNG image formats, the quality value sets
118                      * the zlib compression level (quality / 10) and filter-type (quality % 10).
119                      * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
120                      * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
121                      */
122                     $quality = $quality * 10;
123                     $this->image->setCompressionQuality($quality);
124                     break;
125                 case "image/jpeg":
126                     $quality = get_config('system','jpeg_quality');
127                     if((! $quality) || ($quality > 100))
128                         $quality = JPEG_QUALITY;
129                     $this->image->setCompressionQuality($quality);
130             }
131
132             $this->width  = $this->image->getImageWidth();
133                         $this->height = $this->image->getImageHeight();
134                         $this->valid  = true;
135
136             return true;
137                 }
138
139                 $this->valid = false;
140                 $this->image = @imagecreatefromstring($data);
141                 if($this->image !== FALSE) {
142                         $this->width  = imagesx($this->image);
143                         $this->height = imagesy($this->image);
144                         $this->valid  = true;
145                         imagealphablending($this->image, false);
146                         imagesavealpha($this->image, true);
147
148                         return true;
149                 }
150                 
151                 return false;
152         }
153
154     public function is_valid() {
155         if($this->is_imagick())
156             return ($this->image !== FALSE);
157         return $this->valid;
158     }
159
160     public function getWidth() {
161         if(!$this->is_valid())
162             return FALSE;
163
164         if($this->is_imagick())
165             return $this->image->getImageWidth();
166         return $this->width;
167     }
168
169     public function getHeight() {
170         if(!$this->is_valid())
171             return FALSE;
172
173         if($this->is_imagick())
174             return $this->image->getImageHeight();
175         return $this->height;
176     }
177
178     public function getImage() {
179         if(!$this->is_valid())
180             return FALSE;
181
182         if($this->is_imagick()) {
183             /* Clean it */
184             $this->image = $this->image->deconstructImages();
185             return $this->image;
186         }
187         return $this->image;
188     }
189
190     public function getType() {
191         if(!$this->is_valid())
192             return FALSE;
193
194         return $this->type;
195     }
196
197     public function getExt() {
198         if(!$this->is_valid())
199             return FALSE;
200
201         return $this->types[$this->getType()];
202     }
203
204     public function scaleImage($max) {
205         if(!$this->is_valid())
206             return FALSE;
207
208         if($this->is_imagick()) {
209             /**
210              * If it is not animated, there will be only one iteration here,
211              * so don't bother checking
212              */
213             // Don't forget to go back to the first frame
214             $this->image->setFirstIterator();
215             do {
216
217                                 // FIXME - implement horizantal bias for scaling as in followin GD functions
218                                 // to allow very tall images to be constrained only horizontally. 
219
220                 $this->image->resizeImage($max, $max, imagick::FILTER_LANCZOS, 1, true);
221             } while ($this->image->nextImage());
222
223                         // FIXME - also we need to copy the new dimensions to $this->height, $this->width as other functions
224                         // may rely on it.
225
226             return;
227         }
228
229         $width = $this->width;
230         $height = $this->height;
231
232         $dest_width = $dest_height = 0;
233
234         if((! $width)|| (! $height))
235             return FALSE;
236
237         if($width > $max && $height > $max) {
238
239                         // very tall image (greater than 16:9)
240                         // constrain the width - let the height float.
241
242                         if((($height * 9) / 16) > $width) {
243                                 $dest_width = $max;
244                 $dest_height = intval(( $height * $max ) / $width);
245                         }
246
247                         // else constrain both dimensions
248
249                         elseif($width > $height) {
250                 $dest_width = $max;
251                 $dest_height = intval(( $height * $max ) / $width);
252             }
253             else {
254                 $dest_width = intval(( $width * $max ) / $height);
255                 $dest_height = $max;
256             }
257         }
258         else {
259             if( $width > $max ) {
260                 $dest_width = $max;
261                 $dest_height = intval(( $height * $max ) / $width);
262             }
263             else {
264                 if( $height > $max ) {
265
266                                         // very tall image (greater than 16:9)
267                                         // but width is OK - don't do anything
268
269                                         if((($height * 9) / 16) > $width) {
270                                                 $dest_width = $width;
271                                 $dest_height = $height;
272                                         }
273                                         else {
274                             $dest_width = intval(( $width * $max ) / $height);
275                         $dest_height = $max;
276                                         }
277                 }
278                 else {
279                     $dest_width = $width;
280                     $dest_height = $height;
281                 }
282             }
283         }
284
285
286         $dest = imagecreatetruecolor( $dest_width, $dest_height );
287         imagealphablending($dest, false);
288         imagesavealpha($dest, true);
289         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
290         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
291         if($this->image)
292             imagedestroy($this->image);
293         $this->image = $dest;
294         $this->width  = imagesx($this->image);
295         $this->height = imagesy($this->image);
296     }
297
298     public function rotate($degrees) {
299         if(!$this->is_valid())
300             return FALSE;
301
302         if($this->is_imagick()) {
303             $this->image->setFirstIterator();
304             do {
305                 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
306             } while ($this->image->nextImage());
307             return;
308         }
309
310         $this->image  = imagerotate($this->image,$degrees,0);
311         $this->width  = imagesx($this->image);
312         $this->height = imagesy($this->image);
313     }
314
315     public function flip($horiz = true, $vert = false) {
316         if(!$this->is_valid())
317             return FALSE;
318
319         if($this->is_imagick()) {
320             $this->image->setFirstIterator();
321             do {
322                 if($horiz) $this->image->flipImage();
323                 if($vert) $this->image->flopImage();
324             } while ($this->image->nextImage());
325             return;
326         }
327
328         $w = imagesx($this->image);
329         $h = imagesy($this->image);
330         $flipped = imagecreate($w, $h);
331         if($horiz) {
332             for ($x = 0; $x < $w; $x++) {
333                 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
334             }
335         }
336         if($vert) {
337             for ($y = 0; $y < $h; $y++) {
338                 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
339             }
340         }
341         $this->image = $flipped;
342     }
343
344     public function orient($filename) {
345         // based off comment on http://php.net/manual/en/function.imagerotate.php
346
347         if(!$this->is_valid())
348             return FALSE;
349
350         if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
351             return;
352
353         $exif = @exif_read_data($filename);
354
355                 if(! $exif)
356                         return;
357
358         $ort = $exif['Orientation'];
359
360         switch($ort)
361         {
362             case 1: // nothing
363                 break;
364
365             case 2: // horizontal flip
366                 $this->flip();
367                 break;
368
369             case 3: // 180 rotate left
370                 $this->rotate(180);
371                 break;
372
373             case 4: // vertical flip
374                 $this->flip(false, true);
375                 break;
376
377             case 5: // vertical flip + 90 rotate right
378                 $this->flip(false, true);
379                 $this->rotate(-90);
380                 break;
381
382             case 6: // 90 rotate right
383                 $this->rotate(-90);
384                 break;
385
386             case 7: // horizontal flip + 90 rotate right
387                 $this->flip();
388                 $this->rotate(-90);
389                 break;
390
391             case 8:    // 90 rotate left
392                 $this->rotate(90);
393                 break;
394         }
395     }
396
397
398
399     public function scaleImageUp($min) {
400         if(!$this->is_valid())
401             return FALSE;
402
403         if($this->is_imagick())
404             return $this->scaleImage($min);
405
406         $width = $this->width;
407         $height = $this->height;
408
409         $dest_width = $dest_height = 0;
410
411         if((! $width)|| (! $height))
412             return FALSE;
413
414         if($width < $min && $height < $min) {
415             if($width > $height) {
416                 $dest_width = $min;
417                 $dest_height = intval(( $height * $min ) / $width);
418             }
419             else {
420                 $dest_width = intval(( $width * $min ) / $height);
421                 $dest_height = $min;
422             }
423         }
424         else {
425             if( $width < $min ) {
426                 $dest_width = $min;
427                 $dest_height = intval(( $height * $min ) / $width);
428             }
429             else {
430                 if( $height < $min ) {
431                     $dest_width = intval(( $width * $min ) / $height);
432                     $dest_height = $min;
433                 }
434                 else {
435                     $dest_width = $width;
436                     $dest_height = $height;
437                 }
438             }
439         }
440
441
442         $dest = imagecreatetruecolor( $dest_width, $dest_height );
443         imagealphablending($dest, false);
444         imagesavealpha($dest, true);
445         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
446         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
447         if($this->image)
448             imagedestroy($this->image);
449         $this->image = $dest;
450         $this->width  = imagesx($this->image);
451         $this->height = imagesy($this->image);
452     }
453
454
455
456     public function scaleImageSquare($dim) {
457         if(!$this->is_valid())
458             return FALSE;
459
460         if($this->is_imagick()) {
461             $this->image->setFirstIterator();
462             do {
463                 $this->image->resizeImage($dim, $dim, imagick::FILTER_LANCZOS, 1, false);
464             } while ($this->image->nextImage());
465             return;
466         }
467
468         $dest = imagecreatetruecolor( $dim, $dim );
469         imagealphablending($dest, false);
470         imagesavealpha($dest, true);
471         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
472         imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
473         if($this->image)
474             imagedestroy($this->image);
475         $this->image = $dest;
476         $this->width  = imagesx($this->image);
477         $this->height = imagesy($this->image);
478     }
479
480
481     public function cropImage($max,$x,$y,$w,$h) {
482         if(!$this->is_valid())
483             return FALSE;
484
485         if($this->is_imagick()) {
486             $this->image->setFirstIterator();
487             do {
488                 $this->image->cropImage($w, $h, $x, $y);
489                 /**
490                  * We need to remove the canva,
491                  * or the image is not resized to the crop:
492                  * http://php.net/manual/en/imagick.cropimage.php#97232
493                  */
494                 $this->image->setImagePage(0, 0, 0, 0);
495             } while ($this->image->nextImage());
496             return $this->scaleImage($max);
497         }
498
499         $dest = imagecreatetruecolor( $max, $max );
500         imagealphablending($dest, false);
501         imagesavealpha($dest, true);
502         if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
503         imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
504         if($this->image)
505             imagedestroy($this->image);
506         $this->image = $dest;
507         $this->width  = imagesx($this->image);
508         $this->height = imagesy($this->image);
509     }
510
511     public function saveImage($path) {
512         if(!$this->is_valid())
513             return FALSE;
514
515         $string = $this->imageString();
516         file_put_contents($path, $string);
517     }
518
519     public function imageString() {
520         if(!$this->is_valid())
521             return FALSE;
522
523         if($this->is_imagick()) {
524             /* Clean it */
525             $this->image = $this->image->deconstructImages();
526             $string = $this->image->getImagesBlob();
527             return $string;
528         }
529
530         $quality = FALSE;
531
532         ob_start();
533
534         switch($this->getType()){
535             case "image/png":
536                 $quality = get_config('system','png_quality');
537                 if((! $quality) || ($quality > 9))
538                     $quality = PNG_QUALITY;
539                 imagepng($this->image,NULL, $quality);
540                 break;
541             case "image/jpeg":
542                 $quality = get_config('system','jpeg_quality');
543                 if((! $quality) || ($quality > 100))
544                     $quality = JPEG_QUALITY;
545                 imagejpeg($this->image,NULL,$quality);
546         }
547         $string = ob_get_contents();
548         ob_end_clean();
549
550         return $string;
551     }
552
553
554
555     public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
556
557         $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
558             dbesc($rid)
559         );
560         if(count($r))
561             $guid = $r[0]['guid'];
562         else
563             $guid = get_guid();
564
565         $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
566                 dbesc($rid),
567                 intval($uid),
568                 intval($cid),
569                 intval($scale)
570         );
571         if(count($x)) {
572             $r = q("UPDATE `photo`
573                 set `uid` = %d,
574                 `contact-id` = %d,
575                 `guid` = '%s',
576                 `resource-id` = '%s',
577                 `created` = '%s',
578                 `edited` = '%s',
579                 `filename` = '%s',
580                 `type` = '%s',
581                 `album` = '%s',
582                 `height` = %d,
583                 `width` = %d,
584                 `data` = '%s',
585                 `scale` = %d,
586                 `profile` = %d,
587                 `allow_cid` = '%s',
588                 `allow_gid` = '%s',
589                 `deny_cid` = '%s',
590                 `deny_gid` = '%s'
591                 where id = %d limit 1",
592
593                 intval($uid),
594                 intval($cid),
595                 dbesc($guid),
596                 dbesc($rid),
597                 dbesc(datetime_convert()),
598                 dbesc(datetime_convert()),
599                 dbesc(basename($filename)),
600                 dbesc($this->getType()),
601                 dbesc($album),
602                 intval($this->getHeight()),
603                 intval($this->getWidth()),
604                 dbesc($this->imageString()),
605                 intval($scale),
606                 intval($profile),
607                 dbesc($allow_cid),
608                 dbesc($allow_gid),
609                 dbesc($deny_cid),
610                 dbesc($deny_gid),
611                 intval($x[0]['id'])
612             );
613         }
614         else {
615             $r = q("INSERT INTO `photo`
616                 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
617                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
618                 intval($uid),
619                 intval($cid),
620                 dbesc($guid),
621                 dbesc($rid),
622                 dbesc(datetime_convert()),
623                 dbesc(datetime_convert()),
624                 dbesc(basename($filename)),
625                 dbesc($this->getType()),
626                 dbesc($album),
627                 intval($this->getHeight()),
628                 intval($this->getWidth()),
629                 dbesc($this->imageString()),
630                 intval($scale),
631                 intval($profile),
632                 dbesc($allow_cid),
633                 dbesc($allow_gid),
634                 dbesc($deny_cid),
635                 dbesc($deny_gid)
636             );
637         }
638         return $r;
639     }
640 }}
641
642
643 /**
644  * Guess image mimetype from filename or from Content-Type header
645  *
646  * @arg $filename string Image filename
647  * @arg $fromcurl boolean Check Content-Type header from curl request
648  */
649 function guess_image_type($filename, $fromcurl=false) {
650     logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
651     $type = null;
652     if ($fromcurl) {
653         $a = get_app();
654         $headers=array();
655         $h = explode("\n",$a->get_curl_headers());
656         foreach ($h as $l) {
657             list($k,$v) = array_map("trim", explode(":", trim($l), 2));
658             $headers[$k] = $v;
659         }
660         if (array_key_exists('Content-Type', $headers))
661             $type = $headers['Content-Type'];
662     }
663     if (is_null($type)){
664         // Guessing from extension? Isn't that... dangerous?
665         if(class_exists('Imagick')) {
666             /**
667              * Well, this not much better,
668              * but at least it comes from the data inside the image,
669              * we won't be tricked by a manipulated extension
670              */
671             $image = new Imagick($filename);
672             $type = $image->getImageMimeType();
673         } else {
674             $ext = pathinfo($filename, PATHINFO_EXTENSION);
675             $types = Photo::supportedTypes();
676             $type = "image/jpeg";
677             foreach ($types as $m=>$e){
678                 if ($ext==$e) $type = $m;
679             }
680         }
681     }
682     logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
683     return $type;
684
685 }
686
687 function import_profile_photo($photo,$uid,$cid) {
688
689     $a = get_app();
690
691     $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
692         intval($uid),
693         intval($cid)
694     );
695     if(count($r) && strlen($r[0]['resource-id'])) {
696         $hash = $r[0]['resource-id'];
697     }
698     else {
699         $hash = photo_new_resource();
700     }
701
702     $photo_failure = false;
703
704     $filename = basename($photo);
705     $img_str = fetch_url($photo,true);
706
707     $type = guess_image_type($photo,true);
708     $img = new Photo($img_str, $type);
709     if($img->is_valid()) {
710
711         $img->scaleImageSquare(175);
712
713         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
714
715         if($r === false)
716             $photo_failure = true;
717
718         $img->scaleImage(80);
719
720         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
721
722         if($r === false)
723             $photo_failure = true;
724
725         $img->scaleImage(48);
726
727         $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
728
729         if($r === false)
730             $photo_failure = true;
731
732         $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
733         $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
734         $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
735     }
736     else
737         $photo_failure = true;
738
739     if($photo_failure) {
740         $photo = $a->get_baseurl() . '/images/person-175.jpg';
741         $thumb = $a->get_baseurl() . '/images/person-80.jpg';
742         $micro = $a->get_baseurl() . '/images/person-48.jpg';
743     }
744
745     return(array($photo,$thumb,$micro));
746
747 }