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\Logger;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Photo;
17 use Friendica\Util\Network;
23 * Class to handle images
30 * Put back gd stuff, not everybody have Imagick
40 * @brief supported mimetypes and corresponding file extensions
43 public static function supportedTypes()
45 if (class_exists('Imagick')) {
46 // Imagick::queryFormats won't help us a lot there...
47 // At least, not yet, other parts of friendica uses this array
49 'image/jpeg' => 'jpg',
55 $t['image/jpeg'] ='jpg';
56 if (imagetypes() & IMG_PNG) {
57 $t['image/png'] = 'png';
66 * @param object $data data
67 * @param boolean $type optional, default null
70 public function __construct($data, $type = null)
72 $this->imagick = class_exists('Imagick');
73 $this->types = static::supportedTypes();
74 if (!array_key_exists($type, $this->types)) {
79 if ($this->isImagick() && $this->loadData($data)) {
82 // Failed to load with Imagick, fallback
83 $this->imagick = false;
85 return $this->loadData($data);
92 public function __destruct()
95 if ($this->isImagick()) {
96 $this->image->clear();
97 $this->image->destroy();
100 if (is_resource($this->image)) {
101 imagedestroy($this->image);
109 public function isImagick()
111 return $this->imagick;
115 * @brief Maps Mime types to Imagick formats
116 * @return array With with image formats (mime type as key)
118 public static function getFormatsMap()
121 'image/jpeg' => 'JPG',
122 'image/png' => 'PNG',
129 * @param object $data data
132 private function loadData($data)
134 if ($this->isImagick()) {
135 $this->image = new Imagick();
137 $this->image->readImageBlob($data);
138 } catch (Exception $e) {
139 // Imagick couldn't use the data
144 * Setup the image to the format it will be saved to
146 $map = self::getFormatsMap();
147 $format = $map[$this->type];
148 $this->image->setFormat($format);
150 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
151 $this->image = $this->image->coalesceImages();
154 * setup the compression here, so we'll do it only once
156 switch ($this->getType()) {
158 $quality = Config::get('system', 'png_quality');
159 if ((! $quality) || ($quality > 9)) {
160 $quality = PNG_QUALITY;
163 * From http://www.imagemagick.org/script/command-line-options.php#quality:
165 * 'For the MNG and PNG image formats, the quality value sets
166 * the zlib compression level (quality / 10) and filter-type (quality % 10).
167 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
168 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
170 $quality = $quality * 10;
171 $this->image->setCompressionQuality($quality);
174 $quality = Config::get('system', 'jpeg_quality');
175 if ((! $quality) || ($quality > 100)) {
176 $quality = JPEG_QUALITY;
178 $this->image->setCompressionQuality($quality);
181 // The 'width' and 'height' properties are only used by non-Imagick routines.
182 $this->width = $this->image->getImageWidth();
183 $this->height = $this->image->getImageHeight();
189 $this->valid = false;
190 $this->image = @imagecreatefromstring($data);
191 if ($this->image !== false) {
192 $this->width = imagesx($this->image);
193 $this->height = imagesy($this->image);
195 imagealphablending($this->image, false);
196 imagesavealpha($this->image, true);
207 public function isValid()
209 if ($this->isImagick()) {
210 return ($this->image !== false);
218 public function getWidth()
220 if (!$this->isValid()) {
224 if ($this->isImagick()) {
225 return $this->image->getImageWidth();
233 public function getHeight()
235 if (!$this->isValid()) {
239 if ($this->isImagick()) {
240 return $this->image->getImageHeight();
242 return $this->height;
248 public function getImage()
250 if (!$this->isValid()) {
254 if ($this->isImagick()) {
256 $this->image = $this->image->deconstructImages();
265 public function getType()
267 if (!$this->isValid()) {
277 public function getExt()
279 if (!$this->isValid()) {
283 return $this->types[$this->getType()];
287 * @param integer $max max dimension
290 public function scaleDown($max)
292 if (!$this->isValid()) {
296 $width = $this->getWidth();
297 $height = $this->getHeight();
299 $dest_width = $dest_height = 0;
301 if ((! $width)|| (! $height)) {
305 if ($width > $max && $height > $max) {
306 // very tall image (greater than 16:9)
307 // constrain the width - let the height float.
309 if ((($height * 9) / 16) > $width) {
311 $dest_height = intval(($height * $max) / $width);
312 } elseif ($width > $height) {
313 // else constrain both dimensions
315 $dest_height = intval(($height * $max) / $width);
317 $dest_width = intval(($width * $max) / $height);
323 $dest_height = intval(($height * $max) / $width);
325 if ($height > $max) {
326 // very tall image (greater than 16:9)
327 // but width is OK - don't do anything
329 if ((($height * 9) / 16) > $width) {
330 $dest_width = $width;
331 $dest_height = $height;
333 $dest_width = intval(($width * $max) / $height);
337 $dest_width = $width;
338 $dest_height = $height;
343 return $this->scale($dest_width, $dest_height);
347 * @param integer $degrees degrees to rotate image
350 public function rotate($degrees)
352 if (!$this->isValid()) {
356 if ($this->isImagick()) {
357 $this->image->setFirstIterator();
359 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
360 } while ($this->image->nextImage());
364 // if script dies at this point check memory_limit setting in php.ini
365 $this->image = imagerotate($this->image, $degrees, 0);
366 $this->width = imagesx($this->image);
367 $this->height = imagesy($this->image);
371 * @param boolean $horiz optional, default true
372 * @param boolean $vert optional, default false
375 public function flip($horiz = true, $vert = false)
377 if (!$this->isValid()) {
381 if ($this->isImagick()) {
382 $this->image->setFirstIterator();
385 $this->image->flipImage();
388 $this->image->flopImage();
390 } while ($this->image->nextImage());
394 $w = imagesx($this->image);
395 $h = imagesy($this->image);
396 $flipped = imagecreate($w, $h);
398 for ($x = 0; $x < $w; $x++) {
399 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
403 for ($y = 0; $y < $h; $y++) {
404 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
407 $this->image = $flipped;
411 * @param string $filename filename
414 public function orient($filename)
416 if ($this->isImagick()) {
417 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
418 $orientation = $this->image->getImageOrientation();
419 switch ($orientation) {
420 case Imagick::ORIENTATION_BOTTOMRIGHT:
421 $this->image->rotateimage("#000", 180);
423 case Imagick::ORIENTATION_RIGHTTOP:
424 $this->image->rotateimage("#000", 90);
426 case Imagick::ORIENTATION_LEFTBOTTOM:
427 $this->image->rotateimage("#000", -90);
431 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
434 // based off comment on http://php.net/manual/en/function.imagerotate.php
436 if (!$this->isValid()) {
440 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
444 $exif = @exif_read_data($filename, null, true);
449 $ort = $exif['IFD0']['Orientation'];
455 case 2: // horizontal flip
459 case 3: // 180 rotate left
463 case 4: // vertical flip
464 $this->flip(false, true);
467 case 5: // vertical flip + 90 rotate right
468 $this->flip(false, true);
472 case 6: // 90 rotate right
476 case 7: // horizontal flip + 90 rotate right
481 case 8: // 90 rotate left
486 // Logger::log('exif: ' . print_r($exif,true));
491 * @param integer $min minimum dimension
494 public function scaleUp($min)
496 if (!$this->isValid()) {
500 $width = $this->getWidth();
501 $height = $this->getHeight();
503 $dest_width = $dest_height = 0;
505 if ((!$width)|| (!$height)) {
509 if ($width < $min && $height < $min) {
510 if ($width > $height) {
512 $dest_height = intval(($height * $min) / $width);
514 $dest_width = intval(($width * $min) / $height);
520 $dest_height = intval(($height * $min) / $width);
522 if ($height < $min) {
523 $dest_width = intval(($width * $min) / $height);
526 $dest_width = $width;
527 $dest_height = $height;
532 return $this->scale($dest_width, $dest_height);
536 * @param integer $dim dimension
539 public function scaleToSquare($dim)
541 if (!$this->isValid()) {
545 return $this->scale($dim, $dim);
549 * @brief Scale image to target dimensions
551 * @param int $dest_width
552 * @param int $dest_height
555 private function scale($dest_width, $dest_height)
557 if (!$this->isValid()) {
561 if ($this->isImagick()) {
563 * If it is not animated, there will be only one iteration here,
564 * so don't bother checking
566 // Don't forget to go back to the first frame
567 $this->image->setFirstIterator();
569 // FIXME - implement horizontal bias for scaling as in following GD functions
570 // to allow very tall images to be constrained only horizontally.
571 $this->image->scaleImage($dest_width, $dest_height);
572 } while ($this->image->nextImage());
574 // These may not be necessary anymore
575 $this->width = $this->image->getImageWidth();
576 $this->height = $this->image->getImageHeight();
578 $dest = imagecreatetruecolor($dest_width, $dest_height);
579 imagealphablending($dest, false);
580 imagesavealpha($dest, true);
582 if ($this->type=='image/png') {
583 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
586 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
589 imagedestroy($this->image);
592 $this->image = $dest;
593 $this->width = imagesx($this->image);
594 $this->height = imagesy($this->image);
601 * @param integer $max maximum
602 * @param integer $x x coordinate
603 * @param integer $y y coordinate
604 * @param integer $w width
605 * @param integer $h height
608 public function crop($max, $x, $y, $w, $h)
610 if (!$this->isValid()) {
614 if ($this->isImagick()) {
615 $this->image->setFirstIterator();
617 $this->image->cropImage($w, $h, $x, $y);
619 * We need to remove the canva,
620 * or the image is not resized to the crop:
621 * http://php.net/manual/en/imagick.cropimage.php#97232
623 $this->image->setImagePage(0, 0, 0, 0);
624 } while ($this->image->nextImage());
625 return $this->scaleDown($max);
628 $dest = imagecreatetruecolor($max, $max);
629 imagealphablending($dest, false);
630 imagesavealpha($dest, true);
631 if ($this->type=='image/png') {
632 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
634 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
636 imagedestroy($this->image);
638 $this->image = $dest;
639 $this->width = imagesx($this->image);
640 $this->height = imagesy($this->image);
644 * @param string $path file path
647 public function saveToFilePath($path)
649 if (!$this->isValid()) {
653 $string = $this->asString();
657 $stamp1 = microtime(true);
658 file_put_contents($path, $string);
659 $a->saveTimestamp($stamp1, "file");
663 * @brief Magic method allowing string casting of an Image object
665 * Ex: $data = $Image->asString();
667 * $data = (string) $Image;
671 public function __toString() {
672 return $this->asString();
678 public function asString()
680 if (!$this->isValid()) {
684 if ($this->isImagick()) {
686 $this->image = $this->image->deconstructImages();
687 $string = $this->image->getImagesBlob();
695 // Enable interlacing
696 imageinterlace($this->image, true);
698 switch ($this->getType()) {
700 $quality = Config::get('system', 'png_quality');
701 if ((!$quality) || ($quality > 9)) {
702 $quality = PNG_QUALITY;
704 imagepng($this->image, null, $quality);
707 $quality = Config::get('system', 'jpeg_quality');
708 if ((!$quality) || ($quality > 100)) {
709 $quality = JPEG_QUALITY;
711 imagejpeg($this->image, null, $quality);
713 $string = ob_get_contents();
720 * Guess image mimetype from filename or from Content-Type header
722 * @param string $filename Image filename
723 * @param boolean $fromcurl Check Content-Type header from curl request
724 * @param string $header passed headers to take into account
728 public static function guessType($filename, $fromcurl = false, $header = '')
730 Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
735 $h = explode("\n", $header);
737 $data = array_map("trim", explode(":", trim($l), 2));
738 if (count($data) > 1) {
743 if (array_key_exists('Content-Type', $headers))
744 $type = $headers['Content-Type'];
746 if (is_null($type)) {
747 // Guessing from extension? Isn't that... dangerous?
748 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
750 * Well, this not much better,
751 * but at least it comes from the data inside the image,
752 * we won't be tricked by a manipulated extension
754 $image = new Imagick($filename);
755 $type = $image->getImageMimeType();
756 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
758 $ext = pathinfo($filename, PATHINFO_EXTENSION);
759 $types = self::supportedTypes();
760 $type = "image/jpeg";
761 foreach ($types as $m => $e) {
768 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
773 * @param string $url url
776 public static function getInfoFromURL($url)
784 $data = Cache::get($url);
786 if (is_null($data) || !$data || !is_array($data)) {
787 $img_str = Network::fetchUrl($url, true, $redirects, 4);
793 $filesize = strlen($img_str);
796 if (function_exists("getimagesizefromstring")) {
797 $data = @getimagesizefromstring($img_str);
799 $tempfile = tempnam(get_temppath(), "cache");
802 $stamp1 = microtime(true);
803 file_put_contents($tempfile, $img_str);
804 $a->saveTimestamp($stamp1, "file");
806 $data = getimagesize($tempfile);
809 } catch (Exception $e) {
814 $data["size"] = $filesize;
817 Cache::set($url, $data);
824 * @param integer $width width
825 * @param integer $height height
826 * @param integer $max max
829 public static function getScalingDimensions($width, $height, $max)
831 $dest_width = $dest_height = 0;
833 if ((!$width) || (!$height)) {
837 if ($width > $max && $height > $max) {
838 // very tall image (greater than 16:9)
839 // constrain the width - let the height float.
841 if ((($height * 9) / 16) > $width) {
843 $dest_height = intval(($height * $max) / $width);
844 } elseif ($width > $height) {
845 // else constrain both dimensions
847 $dest_height = intval(($height * $max) / $width);
849 $dest_width = intval(($width * $max) / $height);
855 $dest_height = intval(($height * $max) / $width);
857 if ($height > $max) {
858 // very tall image (greater than 16:9)
859 // but width is OK - don't do anything
861 if ((($height * 9) / 16) > $width) {
862 $dest_width = $width;
863 $dest_height = $height;
865 $dest_width = intval(($width * $max) / $height);
869 $dest_width = $width;
870 $dest_height = $height;
874 return ["width" => $dest_width, "height" => $dest_height];
878 * @brief This function is used by the fromgplus addon
879 * @param object $a App
880 * @param integer $uid user id
881 * @param string $imagedata optional, default empty
882 * @param string $url optional, default empty
885 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
888 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
889 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
893 if (!DBA::isResult($r)) {
894 Logger::log("Can't detect user data for uid ".$uid, Logger::DEBUG);
898 $page_owner_nick = $r[0]['nickname'];
901 /// $default_cid = $r[0]['id'];
902 /// $community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
904 if ((strlen($imagedata) == 0) && ($url == "")) {
905 Logger::log("No image data and no url provided", Logger::DEBUG);
907 } elseif (strlen($imagedata) == 0) {
908 Logger::log("Uploading picture from ".$url, Logger::DEBUG);
910 $stamp1 = microtime(true);
911 $imagedata = @file_get_contents($url);
912 $a->saveTimestamp($stamp1, "file");
915 $maximagesize = Config::get('system', 'maximagesize');
917 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
918 Logger::log("Image exceeds size limit of ".$maximagesize, Logger::DEBUG);
922 $tempfile = tempnam(get_temppath(), "cache");
924 $stamp1 = microtime(true);
925 file_put_contents($tempfile, $imagedata);
926 $a->saveTimestamp($stamp1, "file");
928 $data = getimagesize($tempfile);
930 if (!isset($data["mime"])) {
932 Logger::log("File is no picture", Logger::DEBUG);
936 $Image = new Image($imagedata, $data["mime"]);
938 if (!$Image->isValid()) {
940 Logger::log("Picture is no valid picture", Logger::DEBUG);
944 $Image->orient($tempfile);
947 $max_length = Config::get('system', 'max_image_length');
949 $max_length = MAX_IMAGE_LENGTH;
952 if ($max_length > 0) {
953 $Image->scaleDown($max_length);
956 $width = $Image->getWidth();
957 $height = $Image->getHeight();
959 $hash = Photo::newResource();
963 // Pictures are always public by now
964 //$defperm = '<'.$default_cid.'>';
968 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
971 Logger::log("Picture couldn't be stored", Logger::DEBUG);
975 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
976 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
978 if ($width > 800 || $height > 800) {
979 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
982 if ($width > 640 || $height > 640) {
983 $Image->scaleDown(640);
984 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
986 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
990 if ($width > 320 || $height > 320) {
991 $Image->scaleDown(320);
992 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
994 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
998 if ($width > 160 && $height > 160) {
1002 $min = $Image->getWidth();
1004 $x = ($min - 160) / 2;
1007 if ($Image->getHeight() < $min) {
1008 $min = $Image->getHeight();
1010 $y = ($min - 160) / 2;
1015 $Image->crop(160, $x, $y, $min, $min);
1017 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1019 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1023 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1024 $image["preview"] = $image["full"];
1026 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1027 //if (isset($image["thumb"]))
1028 // $image["preview"] = $image["thumb"];
1030 // Unsure, if this should be activated or deactivated
1031 //if (isset($image["small"]))
1032 // $image["preview"] = $image["small"];
1034 if (isset($image["medium"])) {
1035 $image["preview"] = $image["medium"];