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->saveTimestamp($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
723 * @param string $header passed headers to take into account
727 public static function guessType($filename, $fromcurl = false, $header = '')
729 logger('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
734 $h = explode("\n", $header);
736 $data = array_map("trim", explode(":", trim($l), 2));
737 if (count($data) > 1) {
742 if (array_key_exists('Content-Type', $headers))
743 $type = $headers['Content-Type'];
745 if (is_null($type)) {
746 // Guessing from extension? Isn't that... dangerous?
747 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
749 * Well, this not much better,
750 * but at least it comes from the data inside the image,
751 * we won't be tricked by a manipulated extension
753 $image = new Imagick($filename);
754 $type = $image->getImageMimeType();
755 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
757 $ext = pathinfo($filename, PATHINFO_EXTENSION);
758 $types = self::supportedTypes();
759 $type = "image/jpeg";
760 foreach ($types as $m => $e) {
767 logger('Image: guessType: type='.$type, LOGGER_DEBUG);
772 * @param string $url url
775 public static function getInfoFromURL($url)
783 $data = Cache::get($url);
785 if (is_null($data) || !$data || !is_array($data)) {
786 $img_str = Network::fetchUrl($url, true, $redirects, 4);
792 $filesize = strlen($img_str);
795 if (function_exists("getimagesizefromstring")) {
796 $data = @getimagesizefromstring($img_str);
798 $tempfile = tempnam(get_temppath(), "cache");
801 $stamp1 = microtime(true);
802 file_put_contents($tempfile, $img_str);
803 $a->saveTimestamp($stamp1, "file");
805 $data = getimagesize($tempfile);
808 } catch (Exception $e) {
813 $data["size"] = $filesize;
816 Cache::set($url, $data);
823 * @param integer $width width
824 * @param integer $height height
825 * @param integer $max max
828 public static function getScalingDimensions($width, $height, $max)
830 $dest_width = $dest_height = 0;
832 if ((!$width) || (!$height)) {
836 if ($width > $max && $height > $max) {
837 // very tall image (greater than 16:9)
838 // constrain the width - let the height float.
840 if ((($height * 9) / 16) > $width) {
842 $dest_height = intval(($height * $max) / $width);
843 } elseif ($width > $height) {
844 // else constrain both dimensions
846 $dest_height = intval(($height * $max) / $width);
848 $dest_width = intval(($width * $max) / $height);
854 $dest_height = intval(($height * $max) / $width);
856 if ($height > $max) {
857 // very tall image (greater than 16:9)
858 // but width is OK - don't do anything
860 if ((($height * 9) / 16) > $width) {
861 $dest_width = $width;
862 $dest_height = $height;
864 $dest_width = intval(($width * $max) / $height);
868 $dest_width = $width;
869 $dest_height = $height;
873 return ["width" => $dest_width, "height" => $dest_height];
877 * @brief This function is used by the fromgplus addon
878 * @param object $a App
879 * @param integer $uid user id
880 * @param string $imagedata optional, default empty
881 * @param string $url optional, default empty
884 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
887 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
888 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
892 if (!DBA::isResult($r)) {
893 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
897 $page_owner_nick = $r[0]['nickname'];
900 /// $default_cid = $r[0]['id'];
901 /// $community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
903 if ((strlen($imagedata) == 0) && ($url == "")) {
904 logger("No image data and no url provided", LOGGER_DEBUG);
906 } elseif (strlen($imagedata) == 0) {
907 logger("Uploading picture from ".$url, LOGGER_DEBUG);
909 $stamp1 = microtime(true);
910 $imagedata = @file_get_contents($url);
911 $a->saveTimestamp($stamp1, "file");
914 $maximagesize = Config::get('system', 'maximagesize');
916 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
917 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
921 $tempfile = tempnam(get_temppath(), "cache");
923 $stamp1 = microtime(true);
924 file_put_contents($tempfile, $imagedata);
925 $a->saveTimestamp($stamp1, "file");
927 $data = getimagesize($tempfile);
929 if (!isset($data["mime"])) {
931 logger("File is no picture", LOGGER_DEBUG);
935 $Image = new Image($imagedata, $data["mime"]);
937 if (!$Image->isValid()) {
939 logger("Picture is no valid picture", LOGGER_DEBUG);
943 $Image->orient($tempfile);
946 $max_length = Config::get('system', 'max_image_length');
948 $max_length = MAX_IMAGE_LENGTH;
951 if ($max_length > 0) {
952 $Image->scaleDown($max_length);
955 $width = $Image->getWidth();
956 $height = $Image->getHeight();
958 $hash = Photo::newResource();
962 // Pictures are always public by now
963 //$defperm = '<'.$default_cid.'>';
967 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
970 logger("Picture couldn't be stored", LOGGER_DEBUG);
974 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
975 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
977 if ($width > 800 || $height > 800) {
978 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
981 if ($width > 640 || $height > 640) {
982 $Image->scaleDown(640);
983 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
985 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
989 if ($width > 320 || $height > 320) {
990 $Image->scaleDown(320);
991 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
993 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
997 if ($width > 160 && $height > 160) {
1001 $min = $Image->getWidth();
1003 $x = ($min - 160) / 2;
1006 if ($Image->getHeight() < $min) {
1007 $min = $Image->getHeight();
1009 $y = ($min - 160) / 2;
1014 $Image->crop(160, $x, $y, $min, $min);
1016 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1018 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1022 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1023 $image["preview"] = $image["full"];
1025 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1026 //if (isset($image["thumb"]))
1027 // $image["preview"] = $image["thumb"];
1029 // Unsure, if this should be activated or deactivated
1030 //if (isset($image["small"]))
1031 // $image["preview"] = $image["small"];
1033 if (isset($image["medium"])) {
1034 $image["preview"] = $image["medium"];