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();
45 if($this->is_imagick()) {
46 $this->image = new Imagick();
47 $this->image->readImageBlob($data);
50 * Setup the image to the format of the one we just loaded,
51 * we'll change it to something else if we need to at the time we save it
53 $this->image->setFormat($this->image->getImageFormat());
55 // If it is a gif, it may be animated, get it ready for any future operations
56 if($this->image->getFormat() !== "GIF") $this->image = $this->image->coalesceImages();
58 if (!array_key_exists($type,$this->types)){
63 $this->image = @imagecreatefromstring($data);
64 if($this->image !== FALSE) {
65 $this->width = imagesx($this->image);
66 $this->height = imagesy($this->image);
68 imagealphablending($this->image, false);
69 imagesavealpha($this->image, true);
74 public function __destruct() {
76 if($this->is_imagick()) {
77 $this->image->clear();
78 $this->image->destroy();
81 imagedestroy($this->image);
85 public function is_imagick() {
86 return $this->imagick;
89 public function is_valid() {
90 if($this->is_imagick())
91 return ($this->image !== FALSE);
95 public function getWidth() {
96 if(!$this->is_valid())
99 if($this->is_imagick())
100 return $this->image->getImageWidth();
104 public function getHeight() {
105 if(!$this->is_valid())
108 if($this->is_imagick())
109 return $this->image->getImageHeight();
110 return $this->height;
113 public function getImage() {
114 if(!$this->is_valid())
117 if($this->is_imagick()) {
119 $this->image = $this->image->deconstructImages();
125 public function getType() {
126 if(!$this->is_valid())
129 if($this->is_imagick()) {
130 return $this->image->getImageMimeType();
135 public function getExt() {
136 if(!$this->is_valid())
139 return $this->types[$this->getType()];
142 public function scaleImage($max) {
143 if(!$this->is_valid())
146 if($this->is_imagick()) {
148 * If it is not animated, there will be only one iteration here,
149 * so don't bother checking
151 // Don't forget to go back to the first frame
152 $this->image->setFirstIterator();
154 $this->image->resizeImage($max, $max, imagick::FILTER_LANCZOS, 1, true);
155 } while ($this->image->nextImage());
159 $width = $this->width;
160 $height = $this->height;
162 $dest_width = $dest_height = 0;
164 if((! $width)|| (! $height))
167 if($width > $max && $height > $max) {
168 if($width > $height) {
170 $dest_height = intval(( $height * $max ) / $width);
173 $dest_width = intval(( $width * $max ) / $height);
178 if( $width > $max ) {
180 $dest_height = intval(( $height * $max ) / $width);
183 if( $height > $max ) {
184 $dest_width = intval(( $width * $max ) / $height);
188 $dest_width = $width;
189 $dest_height = $height;
195 $dest = imagecreatetruecolor( $dest_width, $dest_height );
196 imagealphablending($dest, false);
197 imagesavealpha($dest, true);
198 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
199 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
201 imagedestroy($this->image);
202 $this->image = $dest;
203 $this->width = imagesx($this->image);
204 $this->height = imagesy($this->image);
207 public function rotate($degrees) {
208 if(!$this->is_valid())
211 if($this->is_imagick()) {
212 $this->image->setFirstIterator();
214 $this->image->rotateImage(new ImagickPixel(), $degrees);
215 } while ($this->image->nextImage());
219 $this->image = imagerotate($this->image,$degrees,0);
220 $this->width = imagesx($this->image);
221 $this->height = imagesy($this->image);
224 public function flip($horiz = true, $vert = false) {
225 if(!$this->is_valid())
228 if($this->is_imagick()) {
229 $this->image->setFirstIterator();
231 if($horiz) $this->image->flipImage();
232 if($vert) $this->image->flopImage();
233 } while ($this->image->nextImage());
237 $w = imagesx($this->image);
238 $h = imagesy($this->image);
239 $flipped = imagecreate($w, $h);
241 for ($x = 0; $x < $w; $x++) {
242 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
246 for ($y = 0; $y < $h; $y++) {
247 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
250 $this->image = $flipped;
253 public function orient($filename) {
254 // based off comment on http://php.net/manual/en/function.imagerotate.php
256 if(!$this->is_valid())
259 if( (! function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg') )
262 $exif = exif_read_data($filename);
263 $ort = $exif['Orientation'];
270 case 2: // horizontal flip
274 case 3: // 180 rotate left
278 case 4: // vertical flip
279 $this->flip(false, true);
282 case 5: // vertical flip + 90 rotate right
283 $this->flip(false, true);
287 case 6: // 90 rotate right
291 case 7: // horizontal flip + 90 rotate right
296 case 8: // 90 rotate left
304 public function scaleImageUp($min) {
305 if(!$this->is_valid())
308 if($this->is_imagick())
309 return $this->scaleImage($min);
311 $width = $this->width;
312 $height = $this->height;
314 $dest_width = $dest_height = 0;
316 if((! $width)|| (! $height))
319 if($width < $min && $height < $min) {
320 if($width > $height) {
322 $dest_height = intval(( $height * $min ) / $width);
325 $dest_width = intval(( $width * $min ) / $height);
330 if( $width < $min ) {
332 $dest_height = intval(( $height * $min ) / $width);
335 if( $height < $min ) {
336 $dest_width = intval(( $width * $min ) / $height);
340 $dest_width = $width;
341 $dest_height = $height;
347 $dest = imagecreatetruecolor( $dest_width, $dest_height );
348 imagealphablending($dest, false);
349 imagesavealpha($dest, true);
350 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
351 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
353 imagedestroy($this->image);
354 $this->image = $dest;
355 $this->width = imagesx($this->image);
356 $this->height = imagesy($this->image);
361 public function scaleImageSquare($dim) {
362 if(!$this->is_valid())
365 if($this->is_imagick()) {
366 $this->image->setFirstIterator();
368 $this->image->resizeImage($dim, $dim, imagick::FILTER_LANCZOS, 1, false);
369 } while ($this->image->nextImage());
373 $dest = imagecreatetruecolor( $dim, $dim );
374 imagealphablending($dest, false);
375 imagesavealpha($dest, true);
376 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
377 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
379 imagedestroy($this->image);
380 $this->image = $dest;
381 $this->width = imagesx($this->image);
382 $this->height = imagesy($this->image);
386 public function cropImage($max,$x,$y,$w,$h) {
387 if(!$this->is_valid())
390 if($this->is_imagick()) {
391 $this->image->setFirstIterator();
393 $this->image->cropImage($w, $h, $x, $y);
395 * We need to remove the canva,
396 * or the image is not resized to the crop:
397 * http://php.net/manual/en/imagick.cropimage.php#97232
399 $this->image->setImagePage(0, 0, 0, 0);
400 } while ($this->image->nextImage());
401 return $this->scaleImage($max);
404 $dest = imagecreatetruecolor( $max, $max );
405 imagealphablending($dest, false);
406 imagesavealpha($dest, true);
407 if ($this->type=='image/png') imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
408 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
410 imagedestroy($this->image);
411 $this->image = $dest;
412 $this->width = imagesx($this->image);
413 $this->height = imagesy($this->image);
416 public function saveImage($path) {
417 if(!$this->is_valid())
420 $string = $this->imageString();
421 file_put_contents($path, $string);
424 public function imageString() {
425 if(!$this->is_valid())
432 * we should do the conversion/compression at the initialisation i think
433 * This method may be called several times,
434 * and there is no need to do that more than once
437 if(!$this->is_imagick()) ob_start();
439 switch($this->getType()){
441 $quality = get_config('system','png_quality');
442 if((! $quality) || ($quality > 9))
443 $quality = PNG_QUALITY;
444 if($this->is_imagick()) {
446 * From http://www.imagemagick.org/script/command-line-options.php#quality:
448 * 'For the MNG and PNG image formats, the quality value sets
449 * the zlib compression level (quality / 10) and filter-type (quality % 10).
450 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
451 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
453 $quality = $quality * 10;
454 } else imagepng($this->image,NULL, $quality);
457 // We change nothing here, do we?
460 // Convert to jpeg by default
461 $quality = get_config('system','jpeg_quality');
462 if((! $quality) || ($quality > 100))
463 $quality = JPEG_QUALITY;
464 if($this->is_imagick()) {
465 $this->image->setFormat('jpeg');
466 logger('Photo: imageString: Unhandled mime type ('. $this->getType() .'), Imagick format is "'. $this->image->getFormat() .'"', LOGGER_DEBUG);
468 else imagejpeg($this->image,NULL,$quality);
471 if($this->is_imagick()) {
472 if($quality !== FALSE) {
473 // Do we need to iterate for animations?
474 $this->image->setCompressionQuality($quality);
475 $this->image->stripImage();
478 $string = $this->image->getImagesBlob();
480 $string = ob_get_contents();
489 public function store($uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') {
491 $r = q("select `guid` from photo where `resource-id` = '%s' and `guid` != '' limit 1",
495 $guid = $r[0]['guid'];
499 $x = q("select id from photo where `resource-id` = '%s' and uid = %d and `contact-id` = %d and `scale` = %d limit 1",
506 $r = q("UPDATE `photo`
510 `resource-id` = '%s',
525 where id = %d limit 1",
531 dbesc(datetime_convert()),
532 dbesc(datetime_convert()),
533 dbesc(basename($filename)),
534 dbesc($this->getType()),
536 intval($this->getHeight()),
537 intval($this->getWidth()),
538 dbesc($this->imageString()),
549 $r = q("INSERT INTO `photo`
550 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, type, `album`, `height`, `width`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
551 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, '%s', '%s', '%s', '%s' )",
556 dbesc(datetime_convert()),
557 dbesc(datetime_convert()),
558 dbesc(basename($filename)),
559 dbesc($this->getType()),
561 intval($this->getHeight()),
562 intval($this->getWidth()),
563 dbesc($this->imageString()),
578 * Guess image mimetype from filename or from Content-Type header
580 * @arg $filename string Image filename
581 * @arg $fromcurl boolean Check Content-Type header from curl request
583 function guess_image_type($filename, $fromcurl=false) {
584 logger('Photo: guess_image_type: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
589 $h = explode("\n",$a->get_curl_headers());
591 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
594 if (array_key_exists('Content-Type', $headers))
595 $type = $headers['Content-Type'];
598 // Guessing from extension? Isn't that... dangerous?
599 if($this->is_imagick()) {
601 * Well, this not much better,
602 * but at least it comes from the data inside the image,
603 * we won't be tricked by a manipulated extension
605 $image = new Imagick($filename);
606 $type = $image->getImageMimeType();
608 $ext = pathinfo($filename, PATHINFO_EXTENSION);
609 $types = Photo::supportedTypes();
610 $type = "image/jpeg";
611 foreach ($types as $m=>$e){
612 if ($ext==$e) $type = $m;
616 logger('Photo: guess_image_type: type='.$type, LOGGER_DEBUG);
621 function import_profile_photo($photo,$uid,$cid) {
625 $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
630 $hash = $r[0]['resource-id'];
633 $hash = photo_new_resource();
636 $photo_failure = false;
638 $filename = basename($photo);
639 $img_str = fetch_url($photo,true);
641 if($this->is_imagick()) $type = null;
643 // guess mimetype from headers or filename
644 $type = guess_image_type($photo,true);
646 $img = new Photo($img_str, $type);
647 if($img->is_valid()) {
649 $img->scaleImageSquare(175);
651 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
654 $photo_failure = true;
656 $img->scaleImage(80);
658 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
661 $photo_failure = true;
663 $img->scaleImage(48);
665 $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
668 $photo_failure = true;
670 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
671 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
672 $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
675 $photo_failure = true;
678 $photo = $a->get_baseurl() . '/images/person-175.jpg';
679 $thumb = $a->get_baseurl() . '/images/person-80.jpg';
680 $micro = $a->get_baseurl() . '/images/person-48.jpg';
683 return(array($photo,$thumb,$micro));