3 * @file src/Object/Image.php
4 * @brief This file contains the Image class for image processing
6 namespace Friendica\Object;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Photo;
20 * Class to handle images
27 * Put back gd stuff, not everybody have Imagick
37 * @brief supported mimetypes and corresponding file extensions
40 public static function supportedTypes()
42 if (class_exists('Imagick')) {
43 // Imagick::queryFormats won't help us a lot there...
44 // At least, not yet, other parts of friendica uses this array
46 'image/jpeg' => 'jpg',
52 $t['image/jpeg'] ='jpg';
53 if (imagetypes() & IMG_PNG) {
54 $t['image/png'] = 'png';
63 * @param object $data data
64 * @param boolean $type optional, default null
67 public function __construct($data, $type = null)
69 $this->imagick = class_exists('Imagick');
70 $this->types = static::supportedTypes();
71 if (!array_key_exists($type, $this->types)) {
76 if ($this->isImagick() && $this->loadData($data)) {
79 // Failed to load with Imagick, fallback
80 $this->imagick = false;
82 return $this->loadData($data);
89 public function __destruct()
92 if ($this->isImagick()) {
93 $this->image->clear();
94 $this->image->destroy();
97 if (is_resource($this->image)) {
98 imagedestroy($this->image);
106 public function isImagick()
108 return $this->imagick;
112 * @brief Maps Mime types to Imagick formats
113 * @return array With with image formats (mime type as key)
115 public static function getFormatsMap()
118 'image/jpeg' => 'JPG',
119 'image/png' => 'PNG',
126 * @param object $data data
129 private function loadData($data)
131 if ($this->isImagick()) {
132 $this->image = new Imagick();
134 $this->image->readImageBlob($data);
135 } catch (Exception $e) {
136 // Imagick couldn't use the data
141 * Setup the image to the format it will be saved to
143 $map = self::getFormatsMap();
144 $format = $map[$this->type];
145 $this->image->setFormat($format);
147 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
148 $this->image = $this->image->coalesceImages();
151 * setup the compression here, so we'll do it only once
153 switch ($this->getType()) {
155 $quality = Config::get('system', 'png_quality');
156 if ((! $quality) || ($quality > 9)) {
157 $quality = PNG_QUALITY;
160 * From http://www.imagemagick.org/script/command-line-options.php#quality:
162 * 'For the MNG and PNG image formats, the quality value sets
163 * the zlib compression level (quality / 10) and filter-type (quality % 10).
164 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
165 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
167 $quality = $quality * 10;
168 $this->image->setCompressionQuality($quality);
171 $quality = Config::get('system', 'jpeg_quality');
172 if ((! $quality) || ($quality > 100)) {
173 $quality = JPEG_QUALITY;
175 $this->image->setCompressionQuality($quality);
178 // The 'width' and 'height' properties are only used by non-Imagick routines.
179 $this->width = $this->image->getImageWidth();
180 $this->height = $this->image->getImageHeight();
186 $this->valid = false;
187 $this->image = @imagecreatefromstring($data);
188 if ($this->image !== false) {
189 $this->width = imagesx($this->image);
190 $this->height = imagesy($this->image);
192 imagealphablending($this->image, false);
193 imagesavealpha($this->image, true);
204 public function isValid()
206 if ($this->isImagick()) {
207 return ($this->image !== false);
215 public function getWidth()
217 if (!$this->isValid()) {
221 if ($this->isImagick()) {
222 return $this->image->getImageWidth();
230 public function getHeight()
232 if (!$this->isValid()) {
236 if ($this->isImagick()) {
237 return $this->image->getImageHeight();
239 return $this->height;
245 public function getImage()
247 if (!$this->isValid()) {
251 if ($this->isImagick()) {
253 $this->image = $this->image->deconstructImages();
262 public function getType()
264 if (!$this->isValid()) {
274 public function getExt()
276 if (!$this->isValid()) {
280 return $this->types[$this->getType()];
284 * @param integer $max max dimension
287 public function scaleDown($max)
289 if (!$this->isValid()) {
293 $width = $this->getWidth();
294 $height = $this->getHeight();
296 $dest_width = $dest_height = 0;
298 if ((! $width)|| (! $height)) {
302 if ($width > $max && $height > $max) {
303 // very tall image (greater than 16:9)
304 // constrain the width - let the height float.
306 if ((($height * 9) / 16) > $width) {
308 $dest_height = intval(($height * $max) / $width);
309 } elseif ($width > $height) {
310 // else constrain both dimensions
312 $dest_height = intval(($height * $max) / $width);
314 $dest_width = intval(($width * $max) / $height);
320 $dest_height = intval(($height * $max) / $width);
322 if ($height > $max) {
323 // very tall image (greater than 16:9)
324 // but width is OK - don't do anything
326 if ((($height * 9) / 16) > $width) {
327 $dest_width = $width;
328 $dest_height = $height;
330 $dest_width = intval(($width * $max) / $height);
334 $dest_width = $width;
335 $dest_height = $height;
340 return $this->scale($dest_width, $dest_height);
344 * @param integer $degrees degrees to rotate image
347 public function rotate($degrees)
349 if (!$this->isValid()) {
353 if ($this->isImagick()) {
354 $this->image->setFirstIterator();
356 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
357 } while ($this->image->nextImage());
361 // if script dies at this point check memory_limit setting in php.ini
362 $this->image = imagerotate($this->image, $degrees, 0);
363 $this->width = imagesx($this->image);
364 $this->height = imagesy($this->image);
368 * @param boolean $horiz optional, default true
369 * @param boolean $vert optional, default false
372 public function flip($horiz = true, $vert = false)
374 if (!$this->isValid()) {
378 if ($this->isImagick()) {
379 $this->image->setFirstIterator();
382 $this->image->flipImage();
385 $this->image->flopImage();
387 } while ($this->image->nextImage());
391 $w = imagesx($this->image);
392 $h = imagesy($this->image);
393 $flipped = imagecreate($w, $h);
395 for ($x = 0; $x < $w; $x++) {
396 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
400 for ($y = 0; $y < $h; $y++) {
401 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
404 $this->image = $flipped;
408 * @param string $filename filename
411 public function orient($filename)
413 if ($this->isImagick()) {
414 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
415 $orientation = $this->image->getImageOrientation();
416 switch ($orientation) {
417 case Imagick::ORIENTATION_BOTTOMRIGHT:
418 $this->image->rotateimage("#000", 180);
420 case Imagick::ORIENTATION_RIGHTTOP:
421 $this->image->rotateimage("#000", 90);
423 case Imagick::ORIENTATION_LEFTBOTTOM:
424 $this->image->rotateimage("#000", -90);
428 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
431 // based off comment on http://php.net/manual/en/function.imagerotate.php
433 if (!$this->isValid()) {
437 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
441 $exif = @exif_read_data($filename, null, true);
446 $ort = $exif['IFD0']['Orientation'];
452 case 2: // horizontal flip
456 case 3: // 180 rotate left
460 case 4: // vertical flip
461 $this->flip(false, true);
464 case 5: // vertical flip + 90 rotate right
465 $this->flip(false, true);
469 case 6: // 90 rotate right
473 case 7: // horizontal flip + 90 rotate right
478 case 8: // 90 rotate left
483 // logger('exif: ' . print_r($exif,true));
488 * @param integer $min minimum dimension
491 public function scaleUp($min)
493 if (!$this->isValid()) {
497 $width = $this->getWidth();
498 $height = $this->getHeight();
500 $dest_width = $dest_height = 0;
502 if ((!$width)|| (!$height)) {
506 if ($width < $min && $height < $min) {
507 if ($width > $height) {
509 $dest_height = intval(($height * $min) / $width);
511 $dest_width = intval(($width * $min) / $height);
517 $dest_height = intval(($height * $min) / $width);
519 if ($height < $min) {
520 $dest_width = intval(($width * $min) / $height);
523 $dest_width = $width;
524 $dest_height = $height;
529 return $this->scale($dest_width, $dest_height);
533 * @param integer $dim dimension
536 public function scaleToSquare($dim)
538 if (!$this->isValid()) {
542 return $this->scale($dim, $dim);
546 * @brief Scale image to target dimensions
548 * @param int $dest_width
549 * @param int $dest_height
552 private function scale($dest_width, $dest_height)
554 if (!$this->isValid()) {
558 if ($this->isImagick()) {
560 * If it is not animated, there will be only one iteration here,
561 * so don't bother checking
563 // Don't forget to go back to the first frame
564 $this->image->setFirstIterator();
566 // FIXME - implement horizontal bias for scaling as in following GD functions
567 // to allow very tall images to be constrained only horizontally.
568 $this->image->scaleImage($dest_width, $dest_height);
569 } while ($this->image->nextImage());
571 // These may not be necessary anymore
572 $this->width = $this->image->getImageWidth();
573 $this->height = $this->image->getImageHeight();
575 $dest = imagecreatetruecolor($dest_width, $dest_height);
576 imagealphablending($dest, false);
577 imagesavealpha($dest, true);
579 if ($this->type=='image/png') {
580 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
583 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
586 imagedestroy($this->image);
589 $this->image = $dest;
590 $this->width = imagesx($this->image);
591 $this->height = imagesy($this->image);
598 * @param integer $max maximum
599 * @param integer $x x coordinate
600 * @param integer $y y coordinate
601 * @param integer $w width
602 * @param integer $h height
605 public function crop($max, $x, $y, $w, $h)
607 if (!$this->isValid()) {
611 if ($this->isImagick()) {
612 $this->image->setFirstIterator();
614 $this->image->cropImage($w, $h, $x, $y);
616 * We need to remove the canva,
617 * or the image is not resized to the crop:
618 * http://php.net/manual/en/imagick.cropimage.php#97232
620 $this->image->setImagePage(0, 0, 0, 0);
621 } while ($this->image->nextImage());
622 return $this->scaleDown($max);
625 $dest = imagecreatetruecolor($max, $max);
626 imagealphablending($dest, false);
627 imagesavealpha($dest, true);
628 if ($this->type=='image/png') {
629 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
631 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
633 imagedestroy($this->image);
635 $this->image = $dest;
636 $this->width = imagesx($this->image);
637 $this->height = imagesy($this->image);
641 * @param string $path file path
644 public function saveToFilePath($path)
646 if (!$this->isValid()) {
650 $string = $this->asString();
654 $stamp1 = microtime(true);
655 file_put_contents($path, $string);
656 $a->save_timestamp($stamp1, "file");
660 * @brief Magic method allowing string casting of an Image object
662 * Ex: $data = $Image->asString();
664 * $data = (string) $Image;
668 public function __toString() {
669 return $this->asString();
675 public function asString()
677 if (!$this->isValid()) {
681 if ($this->isImagick()) {
683 $this->image = $this->image->deconstructImages();
684 $string = $this->image->getImagesBlob();
692 // Enable interlacing
693 imageinterlace($this->image, true);
695 switch ($this->getType()) {
697 $quality = Config::get('system', 'png_quality');
698 if ((!$quality) || ($quality > 9)) {
699 $quality = PNG_QUALITY;
701 imagepng($this->image, null, $quality);
704 $quality = Config::get('system', 'jpeg_quality');
705 if ((!$quality) || ($quality > 100)) {
706 $quality = JPEG_QUALITY;
708 imagejpeg($this->image, null, $quality);
710 $string = ob_get_contents();
717 * Guess image mimetype from filename or from Content-Type header
719 * @param string $filename Image filename
720 * @param boolean $fromcurl Check Content-Type header from curl request
724 public static function guessType($filename, $fromcurl = false)
726 logger('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
731 $h = explode("\n", $a->get_curl_headers());
733 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
736 if (array_key_exists('Content-Type', $headers))
737 $type = $headers['Content-Type'];
739 if (is_null($type)) {
740 // Guessing from extension? Isn't that... dangerous?
741 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
743 * Well, this not much better,
744 * but at least it comes from the data inside the image,
745 * we won't be tricked by a manipulated extension
747 $image = new Imagick($filename);
748 $type = $image->getImageMimeType();
749 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
751 $ext = pathinfo($filename, PATHINFO_EXTENSION);
752 $types = self::supportedTypes();
753 $type = "image/jpeg";
754 foreach ($types as $m => $e) {
761 logger('Image: guessType: type='.$type, LOGGER_DEBUG);
766 * @param string $url url
769 public static function getInfoFromURL($url)
773 $data = Cache::get($url);
775 if (is_null($data) || !$data || !is_array($data)) {
776 $img_str = fetch_url($url, true, $redirects, 4);
777 $filesize = strlen($img_str);
779 if (function_exists("getimagesizefromstring")) {
780 $data = getimagesizefromstring($img_str);
782 $tempfile = tempnam(get_temppath(), "cache");
785 $stamp1 = microtime(true);
786 file_put_contents($tempfile, $img_str);
787 $a->save_timestamp($stamp1, "file");
789 $data = getimagesize($tempfile);
794 $data["size"] = $filesize;
797 Cache::set($url, $data);
804 * @param integer $width width
805 * @param integer $height height
806 * @param integer $max max
809 public static function getScalingDimensions($width, $height, $max)
811 $dest_width = $dest_height = 0;
813 if ((!$width) || (!$height)) {
817 if ($width > $max && $height > $max) {
818 // very tall image (greater than 16:9)
819 // constrain the width - let the height float.
821 if ((($height * 9) / 16) > $width) {
823 $dest_height = intval(($height * $max) / $width);
824 } elseif ($width > $height) {
825 // else constrain both dimensions
827 $dest_height = intval(($height * $max) / $width);
829 $dest_width = intval(($width * $max) / $height);
835 $dest_height = intval(($height * $max) / $width);
837 if ($height > $max) {
838 // very tall image (greater than 16:9)
839 // but width is OK - don't do anything
841 if ((($height * 9) / 16) > $width) {
842 $dest_width = $width;
843 $dest_height = $height;
845 $dest_width = intval(($width * $max) / $height);
849 $dest_width = $width;
850 $dest_height = $height;
854 return ["width" => $dest_width, "height" => $dest_height];
858 * @brief This function is used by the fromgplus addon
859 * @param object $a App
860 * @param integer $uid user id
861 * @param string $imagedata optional, default empty
862 * @param string $url optional, default empty
865 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
868 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
869 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
873 if (!DBM::is_result($r)) {
874 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
878 $page_owner_nick = $r[0]['nickname'];
881 /// $default_cid = $r[0]['id'];
882 /// $community_page = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
884 if ((strlen($imagedata) == 0) && ($url == "")) {
885 logger("No image data and no url provided", LOGGER_DEBUG);
887 } elseif (strlen($imagedata) == 0) {
888 logger("Uploading picture from ".$url, LOGGER_DEBUG);
890 $stamp1 = microtime(true);
891 $imagedata = @file_get_contents($url);
892 $a->save_timestamp($stamp1, "file");
895 $maximagesize = Config::get('system', 'maximagesize');
897 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
898 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
902 $tempfile = tempnam(get_temppath(), "cache");
904 $stamp1 = microtime(true);
905 file_put_contents($tempfile, $imagedata);
906 $a->save_timestamp($stamp1, "file");
908 $data = getimagesize($tempfile);
910 if (!isset($data["mime"])) {
912 logger("File is no picture", LOGGER_DEBUG);
916 $Image = new Image($imagedata, $data["mime"]);
918 if (!$Image->isValid()) {
920 logger("Picture is no valid picture", LOGGER_DEBUG);
924 $Image->orient($tempfile);
927 $max_length = Config::get('system', 'max_image_length');
929 $max_length = MAX_IMAGE_LENGTH;
932 if ($max_length > 0) {
933 $Image->scaleDown($max_length);
936 $width = $Image->getWidth();
937 $height = $Image->getHeight();
939 $hash = photo_new_resource();
943 // Pictures are always public by now
944 //$defperm = '<'.$default_cid.'>';
948 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
951 logger("Picture couldn't be stored", LOGGER_DEBUG);
955 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
956 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
958 if ($width > 800 || $height > 800) {
959 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
962 if ($width > 640 || $height > 640) {
963 $Image->scaleDown(640);
964 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
966 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
970 if ($width > 320 || $height > 320) {
971 $Image->scaleDown(320);
972 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
974 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
978 if ($width > 160 && $height > 160) {
982 $min = $Image->getWidth();
984 $x = ($min - 160) / 2;
987 if ($Image->getHeight() < $min) {
988 $min = $Image->getHeight();
990 $y = ($min - 160) / 2;
995 $Image->crop(160, $x, $y, $min, $min);
997 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
999 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1003 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1004 $image["preview"] = $image["full"];
1006 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1007 //if (isset($image["thumb"]))
1008 // $image["preview"] = $image["thumb"];
1010 // Unsure, if this should be activated or deactivated
1011 //if (isset($image["small"]))
1012 // $image["preview"] = $image["small"];
1014 if (isset($image["medium"])) {
1015 $image["preview"] = $image["medium"];