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\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Photo;
16 use Friendica\Util\Network;
22 * Class to handle images
29 * Put back gd stuff, not everybody have Imagick
39 * @brief supported mimetypes and corresponding file extensions
42 public static function supportedTypes()
44 if (class_exists('Imagick')) {
45 // Imagick::queryFormats won't help us a lot there...
46 // At least, not yet, other parts of friendica uses this array
48 'image/jpeg' => 'jpg',
54 $t['image/jpeg'] ='jpg';
55 if (imagetypes() & IMG_PNG) {
56 $t['image/png'] = 'png';
65 * @param object $data data
66 * @param boolean $type optional, default null
69 public function __construct($data, $type = null)
71 $this->imagick = class_exists('Imagick');
72 $this->types = static::supportedTypes();
73 if (!array_key_exists($type, $this->types)) {
78 if ($this->isImagick() && $this->loadData($data)) {
81 // Failed to load with Imagick, fallback
82 $this->imagick = false;
84 return $this->loadData($data);
91 public function __destruct()
94 if ($this->isImagick()) {
95 $this->image->clear();
96 $this->image->destroy();
99 if (is_resource($this->image)) {
100 imagedestroy($this->image);
108 public function isImagick()
110 return $this->imagick;
114 * @brief Maps Mime types to Imagick formats
115 * @return array With with image formats (mime type as key)
117 public static function getFormatsMap()
120 'image/jpeg' => 'JPG',
121 'image/png' => 'PNG',
128 * @param object $data data
131 private function loadData($data)
133 if ($this->isImagick()) {
134 $this->image = new Imagick();
136 $this->image->readImageBlob($data);
137 } catch (Exception $e) {
138 // Imagick couldn't use the data
143 * Setup the image to the format it will be saved to
145 $map = self::getFormatsMap();
146 $format = $map[$this->type];
147 $this->image->setFormat($format);
149 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
150 $this->image = $this->image->coalesceImages();
153 * setup the compression here, so we'll do it only once
155 switch ($this->getType()) {
157 $quality = Config::get('system', 'png_quality');
158 if ((! $quality) || ($quality > 9)) {
159 $quality = PNG_QUALITY;
162 * From http://www.imagemagick.org/script/command-line-options.php#quality:
164 * 'For the MNG and PNG image formats, the quality value sets
165 * the zlib compression level (quality / 10) and filter-type (quality % 10).
166 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
167 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
169 $quality = $quality * 10;
170 $this->image->setCompressionQuality($quality);
173 $quality = Config::get('system', 'jpeg_quality');
174 if ((! $quality) || ($quality > 100)) {
175 $quality = JPEG_QUALITY;
177 $this->image->setCompressionQuality($quality);
180 // The 'width' and 'height' properties are only used by non-Imagick routines.
181 $this->width = $this->image->getImageWidth();
182 $this->height = $this->image->getImageHeight();
188 $this->valid = false;
189 $this->image = @imagecreatefromstring($data);
190 if ($this->image !== false) {
191 $this->width = imagesx($this->image);
192 $this->height = imagesy($this->image);
194 imagealphablending($this->image, false);
195 imagesavealpha($this->image, true);
206 public function isValid()
208 if ($this->isImagick()) {
209 return ($this->image !== false);
217 public function getWidth()
219 if (!$this->isValid()) {
223 if ($this->isImagick()) {
224 return $this->image->getImageWidth();
232 public function getHeight()
234 if (!$this->isValid()) {
238 if ($this->isImagick()) {
239 return $this->image->getImageHeight();
241 return $this->height;
247 public function getImage()
249 if (!$this->isValid()) {
253 if ($this->isImagick()) {
255 $this->image = $this->image->deconstructImages();
264 public function getType()
266 if (!$this->isValid()) {
276 public function getExt()
278 if (!$this->isValid()) {
282 return $this->types[$this->getType()];
286 * @param integer $max max dimension
289 public function scaleDown($max)
291 if (!$this->isValid()) {
295 $width = $this->getWidth();
296 $height = $this->getHeight();
298 $dest_width = $dest_height = 0;
300 if ((! $width)|| (! $height)) {
304 if ($width > $max && $height > $max) {
305 // very tall image (greater than 16:9)
306 // constrain the width - let the height float.
308 if ((($height * 9) / 16) > $width) {
310 $dest_height = intval(($height * $max) / $width);
311 } elseif ($width > $height) {
312 // else constrain both dimensions
314 $dest_height = intval(($height * $max) / $width);
316 $dest_width = intval(($width * $max) / $height);
322 $dest_height = intval(($height * $max) / $width);
324 if ($height > $max) {
325 // very tall image (greater than 16:9)
326 // but width is OK - don't do anything
328 if ((($height * 9) / 16) > $width) {
329 $dest_width = $width;
330 $dest_height = $height;
332 $dest_width = intval(($width * $max) / $height);
336 $dest_width = $width;
337 $dest_height = $height;
342 return $this->scale($dest_width, $dest_height);
346 * @param integer $degrees degrees to rotate image
349 public function rotate($degrees)
351 if (!$this->isValid()) {
355 if ($this->isImagick()) {
356 $this->image->setFirstIterator();
358 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
359 } while ($this->image->nextImage());
363 // if script dies at this point check memory_limit setting in php.ini
364 $this->image = imagerotate($this->image, $degrees, 0);
365 $this->width = imagesx($this->image);
366 $this->height = imagesy($this->image);
370 * @param boolean $horiz optional, default true
371 * @param boolean $vert optional, default false
374 public function flip($horiz = true, $vert = false)
376 if (!$this->isValid()) {
380 if ($this->isImagick()) {
381 $this->image->setFirstIterator();
384 $this->image->flipImage();
387 $this->image->flopImage();
389 } while ($this->image->nextImage());
393 $w = imagesx($this->image);
394 $h = imagesy($this->image);
395 $flipped = imagecreate($w, $h);
397 for ($x = 0; $x < $w; $x++) {
398 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
402 for ($y = 0; $y < $h; $y++) {
403 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
406 $this->image = $flipped;
410 * @param string $filename filename
413 public function orient($filename)
415 if ($this->isImagick()) {
416 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
417 $orientation = $this->image->getImageOrientation();
418 switch ($orientation) {
419 case Imagick::ORIENTATION_BOTTOMRIGHT:
420 $this->image->rotateimage("#000", 180);
422 case Imagick::ORIENTATION_RIGHTTOP:
423 $this->image->rotateimage("#000", 90);
425 case Imagick::ORIENTATION_LEFTBOTTOM:
426 $this->image->rotateimage("#000", -90);
430 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
433 // based off comment on http://php.net/manual/en/function.imagerotate.php
435 if (!$this->isValid()) {
439 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
443 $exif = @exif_read_data($filename, null, true);
448 $ort = $exif['IFD0']['Orientation'];
454 case 2: // horizontal flip
458 case 3: // 180 rotate left
462 case 4: // vertical flip
463 $this->flip(false, true);
466 case 5: // vertical flip + 90 rotate right
467 $this->flip(false, true);
471 case 6: // 90 rotate right
475 case 7: // horizontal flip + 90 rotate right
480 case 8: // 90 rotate left
485 // logger('exif: ' . print_r($exif,true));
490 * @param integer $min minimum dimension
493 public function scaleUp($min)
495 if (!$this->isValid()) {
499 $width = $this->getWidth();
500 $height = $this->getHeight();
502 $dest_width = $dest_height = 0;
504 if ((!$width)|| (!$height)) {
508 if ($width < $min && $height < $min) {
509 if ($width > $height) {
511 $dest_height = intval(($height * $min) / $width);
513 $dest_width = intval(($width * $min) / $height);
519 $dest_height = intval(($height * $min) / $width);
521 if ($height < $min) {
522 $dest_width = intval(($width * $min) / $height);
525 $dest_width = $width;
526 $dest_height = $height;
531 return $this->scale($dest_width, $dest_height);
535 * @param integer $dim dimension
538 public function scaleToSquare($dim)
540 if (!$this->isValid()) {
544 return $this->scale($dim, $dim);
548 * @brief Scale image to target dimensions
550 * @param int $dest_width
551 * @param int $dest_height
554 private function scale($dest_width, $dest_height)
556 if (!$this->isValid()) {
560 if ($this->isImagick()) {
562 * If it is not animated, there will be only one iteration here,
563 * so don't bother checking
565 // Don't forget to go back to the first frame
566 $this->image->setFirstIterator();
568 // FIXME - implement horizontal bias for scaling as in following GD functions
569 // to allow very tall images to be constrained only horizontally.
570 $this->image->scaleImage($dest_width, $dest_height);
571 } while ($this->image->nextImage());
573 // These may not be necessary anymore
574 $this->width = $this->image->getImageWidth();
575 $this->height = $this->image->getImageHeight();
577 $dest = imagecreatetruecolor($dest_width, $dest_height);
578 imagealphablending($dest, false);
579 imagesavealpha($dest, true);
581 if ($this->type=='image/png') {
582 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
585 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
588 imagedestroy($this->image);
591 $this->image = $dest;
592 $this->width = imagesx($this->image);
593 $this->height = imagesy($this->image);
600 * @param integer $max maximum
601 * @param integer $x x coordinate
602 * @param integer $y y coordinate
603 * @param integer $w width
604 * @param integer $h height
607 public function crop($max, $x, $y, $w, $h)
609 if (!$this->isValid()) {
613 if ($this->isImagick()) {
614 $this->image->setFirstIterator();
616 $this->image->cropImage($w, $h, $x, $y);
618 * We need to remove the canva,
619 * or the image is not resized to the crop:
620 * http://php.net/manual/en/imagick.cropimage.php#97232
622 $this->image->setImagePage(0, 0, 0, 0);
623 } while ($this->image->nextImage());
624 return $this->scaleDown($max);
627 $dest = imagecreatetruecolor($max, $max);
628 imagealphablending($dest, false);
629 imagesavealpha($dest, true);
630 if ($this->type=='image/png') {
631 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
633 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
635 imagedestroy($this->image);
637 $this->image = $dest;
638 $this->width = imagesx($this->image);
639 $this->height = imagesy($this->image);
643 * @param string $path file path
646 public function saveToFilePath($path)
648 if (!$this->isValid()) {
652 $string = $this->asString();
656 $stamp1 = microtime(true);
657 file_put_contents($path, $string);
658 $a->save_timestamp($stamp1, "file");
662 * @brief Magic method allowing string casting of an Image object
664 * Ex: $data = $Image->asString();
666 * $data = (string) $Image;
670 public function __toString() {
671 return $this->asString();
677 public function asString()
679 if (!$this->isValid()) {
683 if ($this->isImagick()) {
685 $this->image = $this->image->deconstructImages();
686 $string = $this->image->getImagesBlob();
694 // Enable interlacing
695 imageinterlace($this->image, true);
697 switch ($this->getType()) {
699 $quality = Config::get('system', 'png_quality');
700 if ((!$quality) || ($quality > 9)) {
701 $quality = PNG_QUALITY;
703 imagepng($this->image, null, $quality);
706 $quality = Config::get('system', 'jpeg_quality');
707 if ((!$quality) || ($quality > 100)) {
708 $quality = JPEG_QUALITY;
710 imagejpeg($this->image, null, $quality);
712 $string = ob_get_contents();
719 * Guess image mimetype from filename or from Content-Type header
721 * @param string $filename Image filename
722 * @param boolean $fromcurl Check Content-Type header from curl request
726 public static function guessType($filename, $fromcurl = false)
728 logger('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
733 $h = explode("\n", $a->get_curl_headers());
735 $data = array_map("trim", explode(":", trim($l), 2));
736 if (count($data) > 1) {
741 if (array_key_exists('Content-Type', $headers))
742 $type = $headers['Content-Type'];
744 if (is_null($type)) {
745 // Guessing from extension? Isn't that... dangerous?
746 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
748 * Well, this not much better,
749 * but at least it comes from the data inside the image,
750 * we won't be tricked by a manipulated extension
752 $image = new Imagick($filename);
753 $type = $image->getImageMimeType();
754 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
756 $ext = pathinfo($filename, PATHINFO_EXTENSION);
757 $types = self::supportedTypes();
758 $type = "image/jpeg";
759 foreach ($types as $m => $e) {
766 logger('Image: guessType: type='.$type, LOGGER_DEBUG);
771 * @param string $url url
774 public static function getInfoFromURL($url)
782 $data = Cache::get($url);
784 if (is_null($data) || !$data || !is_array($data)) {
785 $img_str = Network::fetchUrl($url, true, $redirects, 4);
791 $filesize = strlen($img_str);
794 if (function_exists("getimagesizefromstring")) {
795 $data = @getimagesizefromstring($img_str);
797 $tempfile = tempnam(get_temppath(), "cache");
800 $stamp1 = microtime(true);
801 file_put_contents($tempfile, $img_str);
802 $a->save_timestamp($stamp1, "file");
804 $data = getimagesize($tempfile);
807 } catch (Exception $e) {
812 $data["size"] = $filesize;
815 Cache::set($url, $data);
822 * @param integer $width width
823 * @param integer $height height
824 * @param integer $max max
827 public static function getScalingDimensions($width, $height, $max)
829 $dest_width = $dest_height = 0;
831 if ((!$width) || (!$height)) {
835 if ($width > $max && $height > $max) {
836 // very tall image (greater than 16:9)
837 // constrain the width - let the height float.
839 if ((($height * 9) / 16) > $width) {
841 $dest_height = intval(($height * $max) / $width);
842 } elseif ($width > $height) {
843 // else constrain both dimensions
845 $dest_height = intval(($height * $max) / $width);
847 $dest_width = intval(($width * $max) / $height);
853 $dest_height = intval(($height * $max) / $width);
855 if ($height > $max) {
856 // very tall image (greater than 16:9)
857 // but width is OK - don't do anything
859 if ((($height * 9) / 16) > $width) {
860 $dest_width = $width;
861 $dest_height = $height;
863 $dest_width = intval(($width * $max) / $height);
867 $dest_width = $width;
868 $dest_height = $height;
872 return ["width" => $dest_width, "height" => $dest_height];
876 * @brief This function is used by the fromgplus addon
877 * @param object $a App
878 * @param integer $uid user id
879 * @param string $imagedata optional, default empty
880 * @param string $url optional, default empty
883 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
886 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
887 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
891 if (!DBA::isResult($r)) {
892 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
896 $page_owner_nick = $r[0]['nickname'];
899 /// $default_cid = $r[0]['id'];
900 /// $community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
902 if ((strlen($imagedata) == 0) && ($url == "")) {
903 logger("No image data and no url provided", LOGGER_DEBUG);
905 } elseif (strlen($imagedata) == 0) {
906 logger("Uploading picture from ".$url, LOGGER_DEBUG);
908 $stamp1 = microtime(true);
909 $imagedata = @file_get_contents($url);
910 $a->save_timestamp($stamp1, "file");
913 $maximagesize = Config::get('system', 'maximagesize');
915 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
916 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
920 $tempfile = tempnam(get_temppath(), "cache");
922 $stamp1 = microtime(true);
923 file_put_contents($tempfile, $imagedata);
924 $a->save_timestamp($stamp1, "file");
926 $data = getimagesize($tempfile);
928 if (!isset($data["mime"])) {
930 logger("File is no picture", LOGGER_DEBUG);
934 $Image = new Image($imagedata, $data["mime"]);
936 if (!$Image->isValid()) {
938 logger("Picture is no valid picture", LOGGER_DEBUG);
942 $Image->orient($tempfile);
945 $max_length = Config::get('system', 'max_image_length');
947 $max_length = MAX_IMAGE_LENGTH;
950 if ($max_length > 0) {
951 $Image->scaleDown($max_length);
954 $width = $Image->getWidth();
955 $height = $Image->getHeight();
957 $hash = Photo::newResource();
961 // Pictures are always public by now
962 //$defperm = '<'.$default_cid.'>';
966 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
969 logger("Picture couldn't be stored", LOGGER_DEBUG);
973 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
974 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
976 if ($width > 800 || $height > 800) {
977 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
980 if ($width > 640 || $height > 640) {
981 $Image->scaleDown(640);
982 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
984 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
988 if ($width > 320 || $height > 320) {
989 $Image->scaleDown(320);
990 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
992 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
996 if ($width > 160 && $height > 160) {
1000 $min = $Image->getWidth();
1002 $x = ($min - 160) / 2;
1005 if ($Image->getHeight() < $min) {
1006 $min = $Image->getHeight();
1008 $y = ($min - 160) / 2;
1013 $Image->crop(160, $x, $y, $min, $min);
1015 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1017 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1021 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1022 $image["preview"] = $image["full"];
1024 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1025 //if (isset($image["thumb"]))
1026 // $image["preview"] = $image["thumb"];
1028 // Unsure, if this should be activated or deactivated
1029 //if (isset($image["small"]))
1030 // $image["preview"] = $image["small"];
1032 if (isset($image["medium"])) {
1033 $image["preview"] = $image["medium"];