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\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';
66 * @param boolean $type optional, default null
67 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
68 * @throws \ImagickException
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 string $data data
131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
132 * @throws \ImagickException
134 private function loadData($data)
136 if ($this->isImagick()) {
137 $this->image = new Imagick();
139 $this->image->readImageBlob($data);
140 } catch (Exception $e) {
141 // Imagick couldn't use the data
146 * Setup the image to the format it will be saved to
148 $map = self::getFormatsMap();
149 $format = $map[$this->type];
150 $this->image->setFormat($format);
152 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
153 $this->image = $this->image->coalesceImages();
156 * setup the compression here, so we'll do it only once
158 switch ($this->getType()) {
160 $quality = Config::get('system', 'png_quality');
161 if ((! $quality) || ($quality > 9)) {
162 $quality = PNG_QUALITY;
165 * From http://www.imagemagick.org/script/command-line-options.php#quality:
167 * 'For the MNG and PNG image formats, the quality value sets
168 * the zlib compression level (quality / 10) and filter-type (quality % 10).
169 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
170 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
172 $quality = $quality * 10;
173 $this->image->setCompressionQuality($quality);
176 $quality = Config::get('system', 'jpeg_quality');
177 if ((! $quality) || ($quality > 100)) {
178 $quality = JPEG_QUALITY;
180 $this->image->setCompressionQuality($quality);
183 // The 'width' and 'height' properties are only used by non-Imagick routines.
184 $this->width = $this->image->getImageWidth();
185 $this->height = $this->image->getImageHeight();
191 $this->valid = false;
192 $this->image = @imagecreatefromstring($data);
193 if ($this->image !== false) {
194 $this->width = imagesx($this->image);
195 $this->height = imagesy($this->image);
197 imagealphablending($this->image, false);
198 imagesavealpha($this->image, true);
209 public function isValid()
211 if ($this->isImagick()) {
212 return ($this->image !== false);
220 public function getWidth()
222 if (!$this->isValid()) {
226 if ($this->isImagick()) {
227 return $this->image->getImageWidth();
235 public function getHeight()
237 if (!$this->isValid()) {
241 if ($this->isImagick()) {
242 return $this->image->getImageHeight();
244 return $this->height;
250 public function getImage()
252 if (!$this->isValid()) {
256 if ($this->isImagick()) {
258 $this->image = $this->image->deconstructImages();
267 public function getType()
269 if (!$this->isValid()) {
279 public function getExt()
281 if (!$this->isValid()) {
285 return $this->types[$this->getType()];
289 * @param integer $max max dimension
292 public function scaleDown($max)
294 if (!$this->isValid()) {
298 $width = $this->getWidth();
299 $height = $this->getHeight();
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 if ((!$width)|| (!$height)) {
507 if ($width < $min && $height < $min) {
508 if ($width > $height) {
510 $dest_height = intval(($height * $min) / $width);
512 $dest_width = intval(($width * $min) / $height);
518 $dest_height = intval(($height * $min) / $width);
520 if ($height < $min) {
521 $dest_width = intval(($width * $min) / $height);
524 $dest_width = $width;
525 $dest_height = $height;
530 return $this->scale($dest_width, $dest_height);
534 * @param integer $dim dimension
537 public function scaleToSquare($dim)
539 if (!$this->isValid()) {
543 return $this->scale($dim, $dim);
547 * @brief Scale image to target dimensions
549 * @param int $dest_width
550 * @param int $dest_height
553 private function scale($dest_width, $dest_height)
555 if (!$this->isValid()) {
559 if ($this->isImagick()) {
561 * If it is not animated, there will be only one iteration here,
562 * so don't bother checking
564 // Don't forget to go back to the first frame
565 $this->image->setFirstIterator();
567 // FIXME - implement horizontal bias for scaling as in following GD functions
568 // to allow very tall images to be constrained only horizontally.
569 $this->image->scaleImage($dest_width, $dest_height);
570 } while ($this->image->nextImage());
572 // These may not be necessary anymore
573 $this->width = $this->image->getImageWidth();
574 $this->height = $this->image->getImageHeight();
576 $dest = imagecreatetruecolor($dest_width, $dest_height);
577 imagealphablending($dest, false);
578 imagesavealpha($dest, true);
580 if ($this->type=='image/png') {
581 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
584 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
587 imagedestroy($this->image);
590 $this->image = $dest;
591 $this->width = imagesx($this->image);
592 $this->height = imagesy($this->image);
599 * @param integer $max maximum
600 * @param integer $x x coordinate
601 * @param integer $y y coordinate
602 * @param integer $w width
603 * @param integer $h height
606 public function crop($max, $x, $y, $w, $h)
608 if (!$this->isValid()) {
612 if ($this->isImagick()) {
613 $this->image->setFirstIterator();
615 $this->image->cropImage($w, $h, $x, $y);
617 * We need to remove the canva,
618 * or the image is not resized to the crop:
619 * http://php.net/manual/en/imagick.cropimage.php#97232
621 $this->image->setImagePage(0, 0, 0, 0);
622 } while ($this->image->nextImage());
623 return $this->scaleDown($max);
626 $dest = imagecreatetruecolor($max, $max);
627 imagealphablending($dest, false);
628 imagesavealpha($dest, true);
629 if ($this->type=='image/png') {
630 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
632 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
634 imagedestroy($this->image);
636 $this->image = $dest;
637 $this->width = imagesx($this->image);
638 $this->height = imagesy($this->image);
642 * @param string $path file path
644 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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;
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
671 public function __toString() {
672 return $this->asString();
677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679 public function asString()
681 if (!$this->isValid()) {
685 if ($this->isImagick()) {
687 $this->image = $this->image->deconstructImages();
688 $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
726 * @throws \ImagickException
728 public static function guessType($filename, $fromcurl = false, $header = '')
730 Logger::log('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::log('Image: guessType: type='.$type, Logger::DEBUG);
772 * @param string $url url
774 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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 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
878 * @param integer $uid user id
879 * @param string $imagedata optional, default empty
880 * @param string $url optional, default empty
882 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
883 * @throws \ImagickException
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'] == User::PAGE_FLAGS_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();
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::log("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"];