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 if($this->is_imagick()) {
210 * If it is not animated, there will be only one iteration here,
211 * so don't bother checking
213 // Don't forget to go back to the first frame
214 $this->image->setFirstIterator();
216 $this->image->resizeImage($max, $max, imagick::FILTER_LANCZOS, 1, true);
217 } while ($this->image->nextImage());
221 $width = $this->width;
222 $height = $this->height;
224 $dest_width = $dest_height = 0;
226 if((! $width)|| (! $height))
229 if($width > $max && $height > $max) {
230 if($width > $height) {
232 $dest_height = intval(( $height * $max ) / $width);
235 $dest_width = intval(( $width * $max ) / $height);
240 if( $width > $max ) {
242 $dest_height = intval(( $height * $max ) / $width);
245 if( $height > $max ) {
246 $dest_width = intval(( $width * $max ) / $height);
250 $dest_width = $width;
251 $dest_height = $height;
257 $dest = imagecreatetruecolor( $dest_width, $dest_height );
258 imagealphablending($dest, false);
259 imagesavealpha($dest, true);
260 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
261 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
263 imagedestroy($this->image);
264 $this->image = $dest;
265 $this->width = imagesx($this->image);
266 $this->height = imagesy($this->image);
269 public function rotate($degrees) {
270 if(!$this->is_valid())
273 if($this->is_imagick()) {
274 $this->image->setFirstIterator();
276 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
277 } while ($this->image->nextImage());
281 $this->image = imagerotate($this->image,$degrees,0);
282 $this->width = imagesx($this->image);
283 $this->height = imagesy($this->image);
286 public function flip($horiz = true, $vert = false) {
287 if(!$this->is_valid())
290 if($this->is_imagick()) {
291 $this->image->setFirstIterator();
293 if($horiz) $this->image->flipImage();
294 if($vert) $this->image->flopImage();
295 } while ($this->image->nextImage());
299 $w = imagesx($this->image);
300 $h = imagesy($this->image);
301 $flipped = imagecreate($w, $h);
303 for ($x = 0; $x < $w; $x++) {
304 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
308 for ($y = 0; $y < $h; $y++) {
309 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
312 $this->image = $flipped;
315 public function orient($filename) {
316 // based off comment on http://php.net/manual/en/function.imagerotate.php
318 if(!$this->is_valid())
321 if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
324 $exif = @exif_read_data($filename);
329 $ort = $exif['Orientation'];
336 case 2: // horizontal flip
340 case 3: // 180 rotate left
344 case 4: // vertical flip
345 $this->flip(false, true);
348 case 5: // vertical flip + 90 rotate right
349 $this->flip(false, true);
353 case 6: // 90 rotate right
357 case 7: // horizontal flip + 90 rotate right
362 case 8: // 90 rotate left
370 public function scaleImageUp($min) {
371 if(!$this->is_valid())
374 if($this->is_imagick())
375 return $this->scaleImage($min);
377 $width = $this->width;
378 $height = $this->height;
380 $dest_width = $dest_height = 0;
382 if((! $width)|| (! $height))
385 if($width < $min && $height < $min) {
386 if($width > $height) {
388 $dest_height = intval(( $height * $min ) / $width);
391 $dest_width = intval(( $width * $min ) / $height);
396 if( $width < $min ) {
398 $dest_height = intval(( $height * $min ) / $width);
401 if( $height < $min ) {
402 $dest_width = intval(( $width * $min ) / $height);
406 $dest_width = $width;
407 $dest_height = $height;
413 $dest = imagecreatetruecolor( $dest_width, $dest_height );
414 imagealphablending($dest, false);
415 imagesavealpha($dest, true);
416 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
417 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
419 imagedestroy($this->image);
420 $this->image = $dest;
421 $this->width = imagesx($this->image);
422 $this->height = imagesy($this->image);
427 public function scaleImageSquare($dim) {
428 if(!$this->is_valid())
431 if($this->is_imagick()) {
432 $this->image->setFirstIterator();
434 $this->image->resizeImage($dim, $dim, imagick::FILTER_LANCZOS, 1, false);
435 } while ($this->image->nextImage());
439 $dest = imagecreatetruecolor( $dim, $dim );
440 imagealphablending($dest, false);
441 imagesavealpha($dest, true);
442 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
443 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
445 imagedestroy($this->image);
446 $this->image = $dest;
447 $this->width = imagesx($this->image);
448 $this->height = imagesy($this->image);
452 public function cropImage($max,$x,$y,$w,$h) {
453 if(!$this->is_valid())
456 if($this->is_imagick()) {
457 $this->image->setFirstIterator();
459 $this->image->cropImage($w, $h, $x, $y);
461 * We need to remove the canva,
462 * or the image is not resized to the crop:
463 * http://php.net/manual/en/imagick.cropimage.php#97232
465 $this->image->setImagePage(0, 0, 0, 0);
466 } while ($this->image->nextImage());
467 return $this->scaleImage($max);
470 $dest = imagecreatetruecolor( $max, $max );
471 imagealphablending($dest, false);
472 imagesavealpha($dest, true);
473 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
474 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
476 imagedestroy($this->image);
477 $this->image = $dest;
478 $this->width = imagesx($this->image);
479 $this->height = imagesy($this->image);
482 public function saveImage($path) {
483 if(!$this->is_valid())
486 $string = $this->imageString();
487 file_put_contents($path, $string);
490 public function imageString() {
491 if(!$this->is_valid())
494 if($this->is_imagick()) {
496 $this->image = $this->image->deconstructImages();
497 $string = $this->image->getImagesBlob();
505 switch($this->getType()){
507 $quality = get_config('system','png_quality');
508 if((! $quality) || ($quality > 9))
509 $quality = PNG_QUALITY;
510 imagepng($this->image,NULL, $quality);
513 $quality = get_config('system','jpeg_quality');
514 if((! $quality) || ($quality > 100))
515 $quality = JPEG_QUALITY;
516 imagejpeg($this->image,NULL,$quality);
518 $string = ob_get_contents();
526 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
528 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
532 $guid = $r[0]['guid'];
536 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
543 $r = q("UPDATE `photo`
547 `resource-id` = '%s',
562 where id = %d limit 1",
568 dbesc(datetime_convert()),
569 dbesc(datetime_convert()),
570 dbesc(basename($filename)),
571 dbesc($this->getType()),
573 intval($this->getHeight()),
574 intval($this->getWidth()),
575 dbesc($this->imageString()),
586 $r = q("INSERT INTO `photo`
587 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
588 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
593 dbesc(datetime_convert()),
594 dbesc(datetime_convert()),
595 dbesc(basename($filename)),
596 dbesc($this->getType()),
598 intval($this->getHeight()),
599 intval($this->getWidth()),
600 dbesc($this->imageString()),
615 * Guess image mimetype from filename or from Content-Type header
617 * @arg $filename string Image filename
618 * @arg $fromcurl boolean Check Content-Type header from curl request
620 function guess_image_type($filename, $fromcurl=false) {
621 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
626 $h = explode("\n",$a->get_curl_headers());
628 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
631 if (array_key_exists('Content-Type', $headers))
632 $type = $headers['Content-Type'];
635 // Guessing from extension? Isn't that... dangerous?
636 if(class_exists('Imagick')) {
638 * Well, this not much better,
639 * but at least it comes from the data inside the image,
640 * we won't be tricked by a manipulated extension
642 $image = new Imagick($filename);
643 $type = $image->getImageMimeType();
645 $ext = pathinfo($filename, PATHINFO_EXTENSION);
646 $types = Photo::supportedTypes();
647 $type = "image/jpeg";
648 foreach ($types as $m=>$e){
649 if ($ext==$e) $type = $m;
653 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
658 function import_profile_photo($photo,$uid,$cid) {
662 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
666 if(count($r) && strlen($r[0]['resource-id'])) {
667 $hash = $r[0]['resource-id'];
670 $hash = photo_new_resource();
673 $photo_failure = false;
675 $filename = basename($photo);
676 $img_str = fetch_url($photo,true);
678 $type = guess_image_type($photo,true);
679 $img = new Photo($img_str, $type);
680 if($img->is_valid()) {
682 $img->scaleImageSquare(175);
684 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
687 $photo_failure = true;
689 $img->scaleImage(80);
691 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
694 $photo_failure = true;
696 $img->scaleImage(48);
698 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
701 $photo_failure = true;
703 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
704 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
705 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
708 $photo_failure = true;
711 $photo = $a->get_baseurl() . '/images/person-175.jpg';
712 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
713 $micro = $a->get_baseurl() . '/images/person-48.jpg';
716 return(array($photo,$thumb,$micro));