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()) {
50 $this->image = new Imagick();
51 $this->image->readImageBlob($data);
54 * Setup the image to the format it will be saved to
56 $map = $this->get_FormatsMap();
57 $format = $map[$type];
58 $this->image->setFormat($format);
60 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
61 $this->image = $this->image->coalesceImages();
64 * setup the compression here, so we'll do it only once
66 switch($this->getType()){
68 $quality = get_config('system','png_quality');
69 if((! $quality) || ($quality > 9))
70 $quality = PNG_QUALITY;
72 * From http://www.imagemagick.org/script/command-line-options.php#quality:
74 * 'For the MNG and PNG image formats, the quality value sets
75 * the zlib compression level (quality / 10) and filter-type (quality % 10).
76 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
77 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
79 $quality = $quality * 10;
80 $this->image->setCompressionQuality($quality);
83 $quality = get_config('system','jpeg_quality');
84 if((! $quality) || ($quality > 100))
85 $quality = JPEG_QUALITY;
86 $this->image->setCompressionQuality($quality);
90 $this->image = @imagecreatefromstring($data);
91 if($this->image !== FALSE) {
92 $this->width = imagesx($this->image);
93 $this->height = imagesy($this->image);
95 imagealphablending($this->image, false);
96 imagesavealpha($this->image, true);
101 public function __destruct() {
103 if($this->is_imagick()) {
104 $this->image->clear();
105 $this->image->destroy();
108 imagedestroy($this->image);
112 public function is_imagick() {
113 return $this->imagick;
117 * Maps Mime types to Imagick formats
119 public function get_FormatsMap() {
121 'image/jpeg' => 'JPG',
122 'image/png' => 'PNG',
128 public function is_valid() {
129 if($this->is_imagick())
130 return ($this->image !== FALSE);
134 public function getWidth() {
135 if(!$this->is_valid())
138 if($this->is_imagick())
139 return $this->image->getImageWidth();
143 public function getHeight() {
144 if(!$this->is_valid())
147 if($this->is_imagick())
148 return $this->image->getImageHeight();
149 return $this->height;
152 public function getImage() {
153 if(!$this->is_valid())
156 if($this->is_imagick()) {
158 $this->image = $this->image->deconstructImages();
164 public function getType() {
165 if(!$this->is_valid())
171 public function getExt() {
172 if(!$this->is_valid())
175 return $this->types[$this->getType()];
178 public function scaleImage($max) {
179 if(!$this->is_valid())
182 if($this->is_imagick()) {
184 * If it is not animated, there will be only one iteration here,
185 * so don't bother checking
187 // Don't forget to go back to the first frame
188 $this->image->setFirstIterator();
190 $this->image->resizeImage($max, $max, imagick::FILTER_LANCZOS, 1, true);
191 } while ($this->image->nextImage());
195 $width = $this->width;
196 $height = $this->height;
198 $dest_width = $dest_height = 0;
200 if((! $width)|| (! $height))
203 if($width > $max && $height > $max) {
204 if($width > $height) {
206 $dest_height = intval(( $height * $max ) / $width);
209 $dest_width = intval(( $width * $max ) / $height);
214 if( $width > $max ) {
216 $dest_height = intval(( $height * $max ) / $width);
219 if( $height > $max ) {
220 $dest_width = intval(( $width * $max ) / $height);
224 $dest_width = $width;
225 $dest_height = $height;
231 $dest = imagecreatetruecolor( $dest_width, $dest_height );
232 imagealphablending($dest, false);
233 imagesavealpha($dest, true);
234 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
235 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
237 imagedestroy($this->image);
238 $this->image = $dest;
239 $this->width = imagesx($this->image);
240 $this->height = imagesy($this->image);
243 public function rotate($degrees) {
244 if(!$this->is_valid())
247 if($this->is_imagick()) {
248 $this->image->setFirstIterator();
250 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
251 } while ($this->image->nextImage());
255 $this->image = imagerotate($this->image,$degrees,0);
256 $this->width = imagesx($this->image);
257 $this->height = imagesy($this->image);
260 public function flip($horiz = true, $vert = false) {
261 if(!$this->is_valid())
264 if($this->is_imagick()) {
265 $this->image->setFirstIterator();
267 if($horiz) $this->image->flipImage();
268 if($vert) $this->image->flopImage();
269 } while ($this->image->nextImage());
273 $w = imagesx($this->image);
274 $h = imagesy($this->image);
275 $flipped = imagecreate($w, $h);
277 for ($x = 0; $x < $w; $x++) {
278 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
282 for ($y = 0; $y < $h; $y++) {
283 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
286 $this->image = $flipped;
289 public function orient($filename) {
290 // based off comment on http://php.net/manual/en/function.imagerotate.php
292 if(!$this->is_valid())
295 if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
298 $exif = @exif_read_data($filename);
303 $ort = $exif['Orientation'];
310 case 2: // horizontal flip
314 case 3: // 180 rotate left
318 case 4: // vertical flip
319 $this->flip(false, true);
322 case 5: // vertical flip + 90 rotate right
323 $this->flip(false, true);
327 case 6: // 90 rotate right
331 case 7: // horizontal flip + 90 rotate right
336 case 8: // 90 rotate left
344 public function scaleImageUp($min) {
345 if(!$this->is_valid())
348 if($this->is_imagick())
349 return $this->scaleImage($min);
351 $width = $this->width;
352 $height = $this->height;
354 $dest_width = $dest_height = 0;
356 if((! $width)|| (! $height))
359 if($width < $min && $height < $min) {
360 if($width > $height) {
362 $dest_height = intval(( $height * $min ) / $width);
365 $dest_width = intval(( $width * $min ) / $height);
370 if( $width < $min ) {
372 $dest_height = intval(( $height * $min ) / $width);
375 if( $height < $min ) {
376 $dest_width = intval(( $width * $min ) / $height);
380 $dest_width = $width;
381 $dest_height = $height;
387 $dest = imagecreatetruecolor( $dest_width, $dest_height );
388 imagealphablending($dest, false);
389 imagesavealpha($dest, true);
390 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
391 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
393 imagedestroy($this->image);
394 $this->image = $dest;
395 $this->width = imagesx($this->image);
396 $this->height = imagesy($this->image);
401 public function scaleImageSquare($dim) {
402 if(!$this->is_valid())
405 if($this->is_imagick()) {
406 $this->image->setFirstIterator();
408 $this->image->resizeImage($dim, $dim, imagick::FILTER_LANCZOS, 1, false);
409 } while ($this->image->nextImage());
413 $dest = imagecreatetruecolor( $dim, $dim );
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, $dim, $dim, $this->width, $this->height);
419 imagedestroy($this->image);
420 $this->image = $dest;
421 $this->width = imagesx($this->image);
422 $this->height = imagesy($this->image);
426 public function cropImage($max,$x,$y,$w,$h) {
427 if(!$this->is_valid())
430 if($this->is_imagick()) {
431 $this->image->setFirstIterator();
433 $this->image->cropImage($w, $h, $x, $y);
435 * We need to remove the canva,
436 * or the image is not resized to the crop:
437 * http://php.net/manual/en/imagick.cropimage.php#97232
439 $this->image->setImagePage(0, 0, 0, 0);
440 } while ($this->image->nextImage());
441 return $this->scaleImage($max);
444 $dest = imagecreatetruecolor( $max, $max );
445 imagealphablending($dest, false);
446 imagesavealpha($dest, true);
447 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
448 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
450 imagedestroy($this->image);
451 $this->image = $dest;
452 $this->width = imagesx($this->image);
453 $this->height = imagesy($this->image);
456 public function saveImage($path) {
457 if(!$this->is_valid())
460 $string = $this->imageString();
461 file_put_contents($path, $string);
464 public function imageString() {
465 if(!$this->is_valid())
468 if($this->is_imagick()) {
470 $this->image = $this->image->deconstructImages();
471 $string = $this->image->getImagesBlob();
479 switch($this->getType()){
481 $quality = get_config('system','png_quality');
482 if((! $quality) || ($quality > 9))
483 $quality = PNG_QUALITY;
484 imagepng($this->image,NULL, $quality);
487 $quality = get_config('system','jpeg_quality');
488 if((! $quality) || ($quality > 100))
489 $quality = JPEG_QUALITY;
490 imagejpeg($this->image,NULL,$quality);
492 $string = ob_get_contents();
500 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
502 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
506 $guid = $r[0]['guid'];
510 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
517 $r = q("UPDATE `photo`
521 `resource-id` = '%s',
536 where id = %d limit 1",
542 dbesc(datetime_convert()),
543 dbesc(datetime_convert()),
544 dbesc(basename($filename)),
545 dbesc($this->getType()),
547 intval($this->getHeight()),
548 intval($this->getWidth()),
549 dbesc($this->imageString()),
560 $r = q("INSERT INTO `photo`
561 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
562 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
567 dbesc(datetime_convert()),
568 dbesc(datetime_convert()),
569 dbesc(basename($filename)),
570 dbesc($this->getType()),
572 intval($this->getHeight()),
573 intval($this->getWidth()),
574 dbesc($this->imageString()),
589 * Guess image mimetype from filename or from Content-Type header
591 * @arg $filename string Image filename
592 * @arg $fromcurl boolean Check Content-Type header from curl request
594 function guess_image_type($filename, $fromcurl=false) {
595 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
600 $h = explode("\n",$a->get_curl_headers());
602 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
605 if (array_key_exists('Content-Type', $headers))
606 $type = $headers['Content-Type'];
609 // Guessing from extension? Isn't that... dangerous?
610 if(class_exists('Imagick')) {
612 * Well, this not much better,
613 * but at least it comes from the data inside the image,
614 * we won't be tricked by a manipulated extension
616 $image = new Imagick($filename);
617 $type = $image->getImageMimeType();
619 $ext = pathinfo($filename, PATHINFO_EXTENSION);
620 $types = Photo::supportedTypes();
621 $type = "image/jpeg";
622 foreach ($types as $m=>$e){
623 if ($ext==$e) $type = $m;
627 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
632 function import_profile_photo($photo,$uid,$cid) {
636 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
641 $hash = $r[0]['resource-id'];
644 $hash = photo_new_resource();
647 $photo_failure = false;
649 $filename = basename($photo);
650 $img_str = fetch_url($photo,true);
652 $type = guess_image_type($photo,true);
653 $img = new Photo($img_str, $type);
654 if($img->is_valid()) {
656 $img->scaleImageSquare(175);
658 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
661 $photo_failure = true;
663 $img->scaleImage(80);
665 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
668 $photo_failure = true;
670 $img->scaleImage(48);
672 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
675 $photo_failure = true;
677 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
678 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
679 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
682 $photo_failure = true;
685 $photo = $a->get_baseurl() . '/images/person-175.jpg';
686 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
687 $micro = $a->get_baseurl() . '/images/person-48.jpg';
690 return(array($photo,$thumb,$micro));