3 if(! class_exists("Photo")) {
9 * Put back gd stuff, not everybody have Imagick
19 * supported mimetypes and corresponding file extensions
21 static function supportedTypes() {
22 if(class_exists('Imagick')) {
24 * Imagick::queryFormats won't help us a lot there...
25 * At least, not yet, other parts of friendica uses this array
28 'image/jpeg' => 'jpg',
34 $t['image/jpeg'] ='jpg';
35 if (imagetypes() & IMG_PNG) $t['image/png'] = 'png';
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)){
49 if($this->is_imagick() && $this->load_data($data)) {
52 // Failed to load with Imagick, fallback
53 $this->imagick = false;
55 return $this->load_data($data);
58 public function __destruct() {
60 if($this->is_imagick()) {
61 $this->image->clear();
62 $this->image->destroy();
65 imagedestroy($this->image);
69 public function is_imagick() {
70 return $this->imagick;
74 * Maps Mime types to Imagick formats
76 public function get_FormatsMap() {
78 'image/jpeg' => 'JPG',
85 private function load_data($data) {
86 if($this->is_imagick()) {
87 $this->image = new Imagick();
89 $this->image->readImageBlob($data);
91 catch (Exception $e) {
92 // Imagick couldn't use the data
97 * Setup the image to the format it will be saved to
99 $map = $this->get_FormatsMap();
100 $format = $map[$type];
101 $this->image->setFormat($format);
103 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
104 $this->image = $this->image->coalesceImages();
107 * setup the compression here, so we'll do it only once
109 switch($this->getType()){
111 $quality = get_config('system','png_quality');
112 if((! $quality) || ($quality > 9))
113 $quality = PNG_QUALITY;
115 * From http://www.imagemagick.org/script/command-line-options.php#quality:
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'
122 $quality = $quality * 10;
123 $this->image->setCompressionQuality($quality);
126 $quality = get_config('system','jpeg_quality');
127 if((! $quality) || ($quality > 100))
128 $quality = JPEG_QUALITY;
129 $this->image->setCompressionQuality($quality);
132 $this->width = $this->image->getImageWidth();
133 $this->height = $this->image->getImageHeight();
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);
145 imagealphablending($this->image, false);
146 imagesavealpha($this->image, true);
154 public function is_valid() {
155 if($this->is_imagick())
156 return ($this->image !== FALSE);
160 public function getWidth() {
161 if(!$this->is_valid())
164 if($this->is_imagick())
165 return $this->image->getImageWidth();
169 public function getHeight() {
170 if(!$this->is_valid())
173 if($this->is_imagick())
174 return $this->image->getImageHeight();
175 return $this->height;
178 public function getImage() {
179 if(!$this->is_valid())
182 if($this->is_imagick()) {
184 $this->image = $this->image->deconstructImages();
190 public function getType() {
191 if(!$this->is_valid())
197 public function getExt() {
198 if(!$this->is_valid())
201 return $this->types[$this->getType()];
204 public function scaleImage($max) {
205 if(!$this->is_valid())
208 $width = $this->width;
209 $height = $this->height;
211 $dest_width = $dest_height = 0;
213 if((! $width)|| (! $height))
216 if($width > $max && $height > $max) {
218 // very tall image (greater than 16:9)
219 // constrain the width - let the height float.
221 if((($height * 9) / 16) > $width) {
223 $dest_height = intval(( $height * $max ) / $width);
226 // else constrain both dimensions
228 elseif($width > $height) {
230 $dest_height = intval(( $height * $max ) / $width);
233 $dest_width = intval(( $width * $max ) / $height);
238 if( $width > $max ) {
240 $dest_height = intval(( $height * $max ) / $width);
243 if( $height > $max ) {
245 // very tall image (greater than 16:9)
246 // but width is OK - don't do anything
248 if((($height * 9) / 16) > $width) {
249 $dest_width = $width;
250 $dest_height = $height;
253 $dest_width = intval(( $width * $max ) / $height);
258 $dest_width = $width;
259 $dest_height = $height;
265 if($this->is_imagick()) {
267 * If it is not animated, there will be only one iteration here,
268 * so don't bother checking
270 // Don't forget to go back to the first frame
271 $this->image->setFirstIterator();
274 // FIXME - implement horizantal bias for scaling as in followin GD functions
275 // to allow very tall images to be constrained only horizontally.
277 $this->image->scaleImage($dest_width, $dest_height);
278 } while ($this->image->nextImage());
280 // FIXME - also we need to copy the new dimensions to $this->height, $this->width as other functions
287 $dest = imagecreatetruecolor( $dest_width, $dest_height );
288 imagealphablending($dest, false);
289 imagesavealpha($dest, true);
290 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
291 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
293 imagedestroy($this->image);
294 $this->image = $dest;
295 $this->width = imagesx($this->image);
296 $this->height = imagesy($this->image);
299 public function rotate($degrees) {
300 if(!$this->is_valid())
303 if($this->is_imagick()) {
304 $this->image->setFirstIterator();
306 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
307 } while ($this->image->nextImage());
311 $this->image = imagerotate($this->image,$degrees,0);
312 $this->width = imagesx($this->image);
313 $this->height = imagesy($this->image);
316 public function flip($horiz = true, $vert = false) {
317 if(!$this->is_valid())
320 if($this->is_imagick()) {
321 $this->image->setFirstIterator();
323 if($horiz) $this->image->flipImage();
324 if($vert) $this->image->flopImage();
325 } while ($this->image->nextImage());
329 $w = imagesx($this->image);
330 $h = imagesy($this->image);
331 $flipped = imagecreate($w, $h);
333 for ($x = 0; $x < $w; $x++) {
334 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
338 for ($y = 0; $y < $h; $y++) {
339 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
342 $this->image = $flipped;
345 public function orient($filename) {
346 // based off comment on http://php.net/manual/en/function.imagerotate.php
348 if(!$this->is_valid())
351 if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
354 $exif = @exif_read_data($filename);
359 $ort = $exif['Orientation'];
366 case 2: // horizontal flip
370 case 3: // 180 rotate left
374 case 4: // vertical flip
375 $this->flip(false, true);
378 case 5: // vertical flip + 90 rotate right
379 $this->flip(false, true);
383 case 6: // 90 rotate right
387 case 7: // horizontal flip + 90 rotate right
392 case 8: // 90 rotate left
400 public function scaleImageUp($min) {
401 if(!$this->is_valid())
405 $width = $this->width;
406 $height = $this->height;
408 $dest_width = $dest_height = 0;
410 if((! $width)|| (! $height))
413 if($width < $min && $height < $min) {
414 if($width > $height) {
416 $dest_height = intval(( $height * $min ) / $width);
419 $dest_width = intval(( $width * $min ) / $height);
424 if( $width < $min ) {
426 $dest_height = intval(( $height * $min ) / $width);
429 if( $height < $min ) {
430 $dest_width = intval(( $width * $min ) / $height);
434 $dest_width = $width;
435 $dest_height = $height;
440 if($this->is_imagick())
441 return $this->scaleImage($dest_width,$dest_height);
443 $dest = imagecreatetruecolor( $dest_width, $dest_height );
444 imagealphablending($dest, false);
445 imagesavealpha($dest, true);
446 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
447 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
449 imagedestroy($this->image);
450 $this->image = $dest;
451 $this->width = imagesx($this->image);
452 $this->height = imagesy($this->image);
457 public function scaleImageSquare($dim) {
458 if(!$this->is_valid())
461 if($this->is_imagick()) {
462 $this->image->setFirstIterator();
464 $this->image->scaleImage($dim, $dim);
465 } while ($this->image->nextImage());
469 $dest = imagecreatetruecolor( $dim, $dim );
470 imagealphablending($dest, false);
471 imagesavealpha($dest, true);
472 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
473 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
475 imagedestroy($this->image);
476 $this->image = $dest;
477 $this->width = imagesx($this->image);
478 $this->height = imagesy($this->image);
482 public function cropImage($max,$x,$y,$w,$h) {
483 if(!$this->is_valid())
486 if($this->is_imagick()) {
487 $this->image->setFirstIterator();
489 $this->image->cropImage($w, $h, $x, $y);
491 * We need to remove the canva,
492 * or the image is not resized to the crop:
493 * http://php.net/manual/en/imagick.cropimage.php#97232
495 $this->image->setImagePage(0, 0, 0, 0);
496 } while ($this->image->nextImage());
497 return $this->scaleImage($max);
500 $dest = imagecreatetruecolor( $max, $max );
501 imagealphablending($dest, false);
502 imagesavealpha($dest, true);
503 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
504 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
506 imagedestroy($this->image);
507 $this->image = $dest;
508 $this->width = imagesx($this->image);
509 $this->height = imagesy($this->image);
512 public function saveImage($path) {
513 if(!$this->is_valid())
516 $string = $this->imageString();
517 file_put_contents($path, $string);
520 public function imageString() {
521 if(!$this->is_valid())
524 if($this->is_imagick()) {
526 $this->image = $this->image->deconstructImages();
527 $string = $this->image->getImagesBlob();
535 switch($this->getType()){
537 $quality = get_config('system','png_quality');
538 if((! $quality) || ($quality > 9))
539 $quality = PNG_QUALITY;
540 imagepng($this->image,NULL, $quality);
543 $quality = get_config('system','jpeg_quality');
544 if((! $quality) || ($quality > 100))
545 $quality = JPEG_QUALITY;
546 imagejpeg($this->image,NULL,$quality);
548 $string = ob_get_contents();
556 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
558 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
562 $guid = $r[0]['guid'];
566 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
573 $r = q("UPDATE `photo`
577 `resource-id` = '%s',
592 where id = %d limit 1",
598 dbesc(datetime_convert()),
599 dbesc(datetime_convert()),
600 dbesc(basename($filename)),
601 dbesc($this->getType()),
603 intval($this->getHeight()),
604 intval($this->getWidth()),
605 dbesc($this->imageString()),
616 $r = q("INSERT INTO `photo`
617 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
618 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
623 dbesc(datetime_convert()),
624 dbesc(datetime_convert()),
625 dbesc(basename($filename)),
626 dbesc($this->getType()),
628 intval($this->getHeight()),
629 intval($this->getWidth()),
630 dbesc($this->imageString()),
645 * Guess image mimetype from filename or from Content-Type header
647 * @arg $filename string Image filename
648 * @arg $fromcurl boolean Check Content-Type header from curl request
650 function guess_image_type($filename, $fromcurl=false) {
651 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
656 $h = explode("\n",$a->get_curl_headers());
658 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
661 if (array_key_exists('Content-Type', $headers))
662 $type = $headers['Content-Type'];
665 // Guessing from extension? Isn't that... dangerous?
666 if(class_exists('Imagick')) {
668 * Well, this not much better,
669 * but at least it comes from the data inside the image,
670 * we won't be tricked by a manipulated extension
672 $image = new Imagick($filename);
673 $type = $image->getImageMimeType();
675 $ext = pathinfo($filename, PATHINFO_EXTENSION);
676 $types = Photo::supportedTypes();
677 $type = "image/jpeg";
678 foreach ($types as $m=>$e){
679 if ($ext==$e) $type = $m;
683 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
688 function import_profile_photo($photo,$uid,$cid) {
692 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
696 if(count($r) && strlen($r[0]['resource-id'])) {
697 $hash = $r[0]['resource-id'];
700 $hash = photo_new_resource();
703 $photo_failure = false;
705 $filename = basename($photo);
706 $img_str = fetch_url($photo,true);
708 $type = guess_image_type($photo,true);
709 $img = new Photo($img_str, $type);
710 if($img->is_valid()) {
712 $img->scaleImageSquare(175);
714 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
717 $photo_failure = true;
719 $img->scaleImage(80);
721 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
724 $photo_failure = true;
726 $img->scaleImage(48);
728 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
731 $photo_failure = true;
733 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
734 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
735 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
738 $photo_failure = true;
741 $photo = $a->get_baseurl() . '/images/person-175.jpg';
742 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
743 $micro = $a->get_baseurl() . '/images/person-48.jpg';
746 return(array($photo,$thumb,$micro));