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 // The 'width' and 'height' properties are only used by non-Imagick routines.
133 $this->width = $this->image->getImageWidth();
134 $this->height = $this->image->getImageHeight();
140 $this->valid = false;
141 $this->image = @imagecreatefromstring($data);
142 if($this->image !== FALSE) {
143 $this->width = imagesx($this->image);
144 $this->height = imagesy($this->image);
146 imagealphablending($this->image, false);
147 imagesavealpha($this->image, true);
155 public function is_valid() {
156 if($this->is_imagick())
157 return ($this->image !== FALSE);
161 public function getWidth() {
162 if(!$this->is_valid())
165 if($this->is_imagick())
166 return $this->image->getImageWidth();
170 public function getHeight() {
171 if(!$this->is_valid())
174 if($this->is_imagick())
175 return $this->image->getImageHeight();
176 return $this->height;
179 public function getImage() {
180 if(!$this->is_valid())
183 if($this->is_imagick()) {
185 $this->image = $this->image->deconstructImages();
191 public function getType() {
192 if(!$this->is_valid())
198 public function getExt() {
199 if(!$this->is_valid())
202 return $this->types[$this->getType()];
205 public function scaleImage($max) {
206 if(!$this->is_valid())
209 $width = $this->getWidth();
210 $height = $this->getHeight();
212 $dest_width = $dest_height = 0;
214 if((! $width)|| (! $height))
217 if($width > $max && $height > $max) {
219 // very tall image (greater than 16:9)
220 // constrain the width - let the height float.
222 if((($height * 9) / 16) > $width) {
224 $dest_height = intval(( $height * $max ) / $width);
227 // else constrain both dimensions
229 elseif($width > $height) {
231 $dest_height = intval(( $height * $max ) / $width);
234 $dest_width = intval(( $width * $max ) / $height);
239 if( $width > $max ) {
241 $dest_height = intval(( $height * $max ) / $width);
244 if( $height > $max ) {
246 // very tall image (greater than 16:9)
247 // but width is OK - don't do anything
249 if((($height * 9) / 16) > $width) {
250 $dest_width = $width;
251 $dest_height = $height;
254 $dest_width = intval(( $width * $max ) / $height);
259 $dest_width = $width;
260 $dest_height = $height;
266 if($this->is_imagick()) {
268 * If it is not animated, there will be only one iteration here,
269 * so don't bother checking
271 // Don't forget to go back to the first frame
272 $this->image->setFirstIterator();
275 // FIXME - implement horizantal bias for scaling as in followin GD functions
276 // to allow very tall images to be constrained only horizontally.
278 $this->image->scaleImage($dest_width, $dest_height);
279 } while ($this->image->nextImage());
281 // These may not be necessary any more
282 $this->width = $this->image->getImageWidth();
283 $this->height = $this->image->getImageHeight();
289 $dest = imagecreatetruecolor( $dest_width, $dest_height );
290 imagealphablending($dest, false);
291 imagesavealpha($dest, true);
292 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
293 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
295 imagedestroy($this->image);
296 $this->image = $dest;
297 $this->width = imagesx($this->image);
298 $this->height = imagesy($this->image);
301 public function rotate($degrees) {
302 if(!$this->is_valid())
305 if($this->is_imagick()) {
306 $this->image->setFirstIterator();
308 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
309 } while ($this->image->nextImage());
313 $this->image = imagerotate($this->image,$degrees,0);
314 $this->width = imagesx($this->image);
315 $this->height = imagesy($this->image);
318 public function flip($horiz = true, $vert = false) {
319 if(!$this->is_valid())
322 if($this->is_imagick()) {
323 $this->image->setFirstIterator();
325 if($horiz) $this->image->flipImage();
326 if($vert) $this->image->flopImage();
327 } while ($this->image->nextImage());
331 $w = imagesx($this->image);
332 $h = imagesy($this->image);
333 $flipped = imagecreate($w, $h);
335 for ($x = 0; $x < $w; $x++) {
336 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
340 for ($y = 0; $y < $h; $y++) {
341 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
344 $this->image = $flipped;
347 public function orient($filename) {
348 // based off comment on http://php.net/manual/en/function.imagerotate.php
350 if(!$this->is_valid())
353 if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
356 $exif = @exif_read_data($filename);
361 $ort = $exif['Orientation'];
368 case 2: // horizontal flip
372 case 3: // 180 rotate left
376 case 4: // vertical flip
377 $this->flip(false, true);
380 case 5: // vertical flip + 90 rotate right
381 $this->flip(false, true);
385 case 6: // 90 rotate right
389 case 7: // horizontal flip + 90 rotate right
394 case 8: // 90 rotate left
402 public function scaleImageUp($min) {
403 if(!$this->is_valid())
407 $width = $this->getWidth();
408 $height = $this->getHeight();
410 $dest_width = $dest_height = 0;
412 if((! $width)|| (! $height))
415 if($width < $min && $height < $min) {
416 if($width > $height) {
418 $dest_height = intval(( $height * $min ) / $width);
421 $dest_width = intval(( $width * $min ) / $height);
426 if( $width < $min ) {
428 $dest_height = intval(( $height * $min ) / $width);
431 if( $height < $min ) {
432 $dest_width = intval(( $width * $min ) / $height);
436 $dest_width = $width;
437 $dest_height = $height;
442 if($this->is_imagick())
443 return $this->scaleImage($dest_width,$dest_height);
445 $dest = imagecreatetruecolor( $dest_width, $dest_height );
446 imagealphablending($dest, false);
447 imagesavealpha($dest, true);
448 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
449 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
451 imagedestroy($this->image);
452 $this->image = $dest;
453 $this->width = imagesx($this->image);
454 $this->height = imagesy($this->image);
459 public function scaleImageSquare($dim) {
460 if(!$this->is_valid())
463 if($this->is_imagick()) {
464 $this->image->setFirstIterator();
466 $this->image->scaleImage($dim, $dim);
467 } while ($this->image->nextImage());
471 $dest = imagecreatetruecolor( $dim, $dim );
472 imagealphablending($dest, false);
473 imagesavealpha($dest, true);
474 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
475 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
477 imagedestroy($this->image);
478 $this->image = $dest;
479 $this->width = imagesx($this->image);
480 $this->height = imagesy($this->image);
484 public function cropImage($max,$x,$y,$w,$h) {
485 if(!$this->is_valid())
488 if($this->is_imagick()) {
489 $this->image->setFirstIterator();
491 $this->image->cropImage($w, $h, $x, $y);
493 * We need to remove the canva,
494 * or the image is not resized to the crop:
495 * http://php.net/manual/en/imagick.cropimage.php#97232
497 $this->image->setImagePage(0, 0, 0, 0);
498 } while ($this->image->nextImage());
499 return $this->scaleImage($max);
502 $dest = imagecreatetruecolor( $max, $max );
503 imagealphablending($dest, false);
504 imagesavealpha($dest, true);
505 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
506 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
508 imagedestroy($this->image);
509 $this->image = $dest;
510 $this->width = imagesx($this->image);
511 $this->height = imagesy($this->image);
514 public function saveImage($path) {
515 if(!$this->is_valid())
518 $string = $this->imageString();
519 file_put_contents($path, $string);
522 public function imageString() {
523 if(!$this->is_valid())
526 if($this->is_imagick()) {
528 $this->image = $this->image->deconstructImages();
529 $string = $this->image->getImagesBlob();
537 switch($this->getType()){
539 $quality = get_config('system','png_quality');
540 if((! $quality) || ($quality > 9))
541 $quality = PNG_QUALITY;
542 imagepng($this->image,NULL, $quality);
545 $quality = get_config('system','jpeg_quality');
546 if((! $quality) || ($quality > 100))
547 $quality = JPEG_QUALITY;
548 imagejpeg($this->image,NULL,$quality);
550 $string = ob_get_contents();
558 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
560 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
564 $guid = $r[0]['guid'];
568 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
575 $r = q("UPDATE `photo`
579 `resource-id` = '%s',
594 where id = %d limit 1",
600 dbesc(datetime_convert()),
601 dbesc(datetime_convert()),
602 dbesc(basename($filename)),
603 dbesc($this->getType()),
605 intval($this->getHeight()),
606 intval($this->getWidth()),
607 dbesc($this->imageString()),
618 $r = q("INSERT INTO `photo`
619 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
620 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
625 dbesc(datetime_convert()),
626 dbesc(datetime_convert()),
627 dbesc(basename($filename)),
628 dbesc($this->getType()),
630 intval($this->getHeight()),
631 intval($this->getWidth()),
632 dbesc($this->imageString()),
647 * Guess image mimetype from filename or from Content-Type header
649 * @arg $filename string Image filename
650 * @arg $fromcurl boolean Check Content-Type header from curl request
652 function guess_image_type($filename, $fromcurl=false) {
653 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
658 $h = explode("\n",$a->get_curl_headers());
660 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
663 if (array_key_exists('Content-Type', $headers))
664 $type = $headers['Content-Type'];
667 // Guessing from extension? Isn't that... dangerous?
668 if(class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
670 * Well, this not much better,
671 * but at least it comes from the data inside the image,
672 * we won't be tricked by a manipulated extension
674 $image = new Imagick($filename);
675 $type = $image->getImageMimeType();
677 $ext = pathinfo($filename, PATHINFO_EXTENSION);
678 $types = Photo::supportedTypes();
679 $type = "image/jpeg";
680 foreach ($types as $m=>$e){
681 if ($ext==$e) $type = $m;
685 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
690 function import_profile_photo($photo,$uid,$cid) {
694 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
698 if(count($r) && strlen($r[0]['resource-id'])) {
699 $hash = $r[0]['resource-id'];
702 $hash = photo_new_resource();
705 $photo_failure = false;
707 $filename = basename($photo);
708 $img_str = fetch_url($photo,true);
710 $type = guess_image_type($photo,true);
711 $img = new Photo($img_str, $type);
712 if($img->is_valid()) {
714 $img->scaleImageSquare(175);
716 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
719 $photo_failure = true;
721 $img->scaleImage(80);
723 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
726 $photo_failure = true;
728 $img->scaleImage(48);
730 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
733 $photo_failure = true;
735 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
736 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
737 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
740 $photo_failure = true;
743 $photo = $a->get_baseurl() . '/images/person-175.jpg';
744 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
745 $micro = $a->get_baseurl() . '/images/person-48.jpg';
748 return(array($photo,$thumb,$micro));