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 $dest_width = $dest_height = 0;
303 if ((! $width)|| (! $height)) {
307 if ($width > $max && $height > $max) {
308 // very tall image (greater than 16:9)
309 // constrain the width - let the height float.
311 if ((($height * 9) / 16) > $width) {
313 $dest_height = intval(($height * $max) / $width);
314 } elseif ($width > $height) {
315 // else constrain both dimensions
317 $dest_height = intval(($height * $max) / $width);
319 $dest_width = intval(($width * $max) / $height);
325 $dest_height = intval(($height * $max) / $width);
327 if ($height > $max) {
328 // very tall image (greater than 16:9)
329 // but width is OK - don't do anything
331 if ((($height * 9) / 16) > $width) {
332 $dest_width = $width;
333 $dest_height = $height;
335 $dest_width = intval(($width * $max) / $height);
339 $dest_width = $width;
340 $dest_height = $height;
345 return $this->scale($dest_width, $dest_height);
349 * @param integer $degrees degrees to rotate image
352 public function rotate($degrees)
354 if (!$this->isValid()) {
358 if ($this->isImagick()) {
359 $this->image->setFirstIterator();
361 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
362 } while ($this->image->nextImage());
366 // if script dies at this point check memory_limit setting in php.ini
367 $this->image = imagerotate($this->image, $degrees, 0);
368 $this->width = imagesx($this->image);
369 $this->height = imagesy($this->image);
373 * @param boolean $horiz optional, default true
374 * @param boolean $vert optional, default false
377 public function flip($horiz = true, $vert = false)
379 if (!$this->isValid()) {
383 if ($this->isImagick()) {
384 $this->image->setFirstIterator();
387 $this->image->flipImage();
390 $this->image->flopImage();
392 } while ($this->image->nextImage());
396 $w = imagesx($this->image);
397 $h = imagesy($this->image);
398 $flipped = imagecreate($w, $h);
400 for ($x = 0; $x < $w; $x++) {
401 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
405 for ($y = 0; $y < $h; $y++) {
406 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
409 $this->image = $flipped;
413 * @param string $filename filename
416 public function orient($filename)
418 if ($this->isImagick()) {
419 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
420 $orientation = $this->image->getImageOrientation();
421 switch ($orientation) {
422 case Imagick::ORIENTATION_BOTTOMRIGHT:
423 $this->image->rotateimage("#000", 180);
425 case Imagick::ORIENTATION_RIGHTTOP:
426 $this->image->rotateimage("#000", 90);
428 case Imagick::ORIENTATION_LEFTBOTTOM:
429 $this->image->rotateimage("#000", -90);
433 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
436 // based off comment on http://php.net/manual/en/function.imagerotate.php
438 if (!$this->isValid()) {
442 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
446 $exif = @exif_read_data($filename, null, true);
451 $ort = $exif['IFD0']['Orientation'];
457 case 2: // horizontal flip
461 case 3: // 180 rotate left
465 case 4: // vertical flip
466 $this->flip(false, true);
469 case 5: // vertical flip + 90 rotate right
470 $this->flip(false, true);
474 case 6: // 90 rotate right
478 case 7: // horizontal flip + 90 rotate right
483 case 8: // 90 rotate left
488 // Logger::log('exif: ' . print_r($exif,true));
493 * @param integer $min minimum dimension
496 public function scaleUp($min)
498 if (!$this->isValid()) {
502 $width = $this->getWidth();
503 $height = $this->getHeight();
505 $dest_width = $dest_height = 0;
507 if ((!$width)|| (!$height)) {
511 if ($width < $min && $height < $min) {
512 if ($width > $height) {
514 $dest_height = intval(($height * $min) / $width);
516 $dest_width = intval(($width * $min) / $height);
522 $dest_height = intval(($height * $min) / $width);
524 if ($height < $min) {
525 $dest_width = intval(($width * $min) / $height);
528 $dest_width = $width;
529 $dest_height = $height;
534 return $this->scale($dest_width, $dest_height);
538 * @param integer $dim dimension
541 public function scaleToSquare($dim)
543 if (!$this->isValid()) {
547 return $this->scale($dim, $dim);
551 * @brief Scale image to target dimensions
553 * @param int $dest_width
554 * @param int $dest_height
557 private function scale($dest_width, $dest_height)
559 if (!$this->isValid()) {
563 if ($this->isImagick()) {
565 * If it is not animated, there will be only one iteration here,
566 * so don't bother checking
568 // Don't forget to go back to the first frame
569 $this->image->setFirstIterator();
571 // FIXME - implement horizontal bias for scaling as in following GD functions
572 // to allow very tall images to be constrained only horizontally.
573 $this->image->scaleImage($dest_width, $dest_height);
574 } while ($this->image->nextImage());
576 // These may not be necessary anymore
577 $this->width = $this->image->getImageWidth();
578 $this->height = $this->image->getImageHeight();
580 $dest = imagecreatetruecolor($dest_width, $dest_height);
581 imagealphablending($dest, false);
582 imagesavealpha($dest, true);
584 if ($this->type=='image/png') {
585 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
588 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
591 imagedestroy($this->image);
594 $this->image = $dest;
595 $this->width = imagesx($this->image);
596 $this->height = imagesy($this->image);
603 * @param integer $max maximum
604 * @param integer $x x coordinate
605 * @param integer $y y coordinate
606 * @param integer $w width
607 * @param integer $h height
610 public function crop($max, $x, $y, $w, $h)
612 if (!$this->isValid()) {
616 if ($this->isImagick()) {
617 $this->image->setFirstIterator();
619 $this->image->cropImage($w, $h, $x, $y);
621 * We need to remove the canva,
622 * or the image is not resized to the crop:
623 * http://php.net/manual/en/imagick.cropimage.php#97232
625 $this->image->setImagePage(0, 0, 0, 0);
626 } while ($this->image->nextImage());
627 return $this->scaleDown($max);
630 $dest = imagecreatetruecolor($max, $max);
631 imagealphablending($dest, false);
632 imagesavealpha($dest, true);
633 if ($this->type=='image/png') {
634 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
636 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
638 imagedestroy($this->image);
640 $this->image = $dest;
641 $this->width = imagesx($this->image);
642 $this->height = imagesy($this->image);
646 * @param string $path file path
648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
650 public function saveToFilePath($path)
652 if (!$this->isValid()) {
656 $string = $this->asString();
660 $stamp1 = microtime(true);
661 file_put_contents($path, $string);
662 $a->saveTimestamp($stamp1, "file");
666 * @brief Magic method allowing string casting of an Image object
668 * Ex: $data = $Image->asString();
670 * $data = (string) $Image;
673 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675 public function __toString() {
676 return $this->asString();
681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
683 public function asString()
685 if (!$this->isValid()) {
689 if ($this->isImagick()) {
691 $this->image = $this->image->deconstructImages();
692 $string = $this->image->getImagesBlob();
700 // Enable interlacing
701 imageinterlace($this->image, true);
703 switch ($this->getType()) {
705 $quality = Config::get('system', 'png_quality');
706 if ((!$quality) || ($quality > 9)) {
707 $quality = PNG_QUALITY;
709 imagepng($this->image, null, $quality);
712 $quality = Config::get('system', 'jpeg_quality');
713 if ((!$quality) || ($quality > 100)) {
714 $quality = JPEG_QUALITY;
716 imagejpeg($this->image, null, $quality);
718 $string = ob_get_contents();
725 * Guess image mimetype from filename or from Content-Type header
727 * @param string $filename Image filename
728 * @param boolean $fromcurl Check Content-Type header from curl request
729 * @param string $header passed headers to take into account
732 * @throws \ImagickException
734 public static function guessType($filename, $fromcurl = false, $header = '')
736 Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
741 $h = explode("\n", $header);
743 $data = array_map("trim", explode(":", trim($l), 2));
744 if (count($data) > 1) {
749 if (array_key_exists('Content-Type', $headers))
750 $type = $headers['Content-Type'];
752 if (is_null($type)) {
753 // Guessing from extension? Isn't that... dangerous?
754 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
756 * Well, this not much better,
757 * but at least it comes from the data inside the image,
758 * we won't be tricked by a manipulated extension
760 $image = new Imagick($filename);
761 $type = $image->getImageMimeType();
762 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
764 $ext = pathinfo($filename, PATHINFO_EXTENSION);
765 $types = self::supportedTypes();
766 $type = "image/jpeg";
767 foreach ($types as $m => $e) {
774 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
779 * @param string $url url
781 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
783 public static function getInfoFromURL($url)
791 $data = Cache::get($url);
793 if (is_null($data) || !$data || !is_array($data)) {
794 $img_str = Network::fetchUrl($url, true, $redirects, 4);
800 $filesize = strlen($img_str);
803 if (function_exists("getimagesizefromstring")) {
804 $data = @getimagesizefromstring($img_str);
806 $tempfile = tempnam(get_temppath(), "cache");
809 $stamp1 = microtime(true);
810 file_put_contents($tempfile, $img_str);
811 $a->saveTimestamp($stamp1, "file");
813 $data = getimagesize($tempfile);
816 } catch (Exception $e) {
821 $data["size"] = $filesize;
824 Cache::set($url, $data);
831 * @param integer $width width
832 * @param integer $height height
833 * @param integer $max max
836 public static function getScalingDimensions($width, $height, $max)
838 $dest_width = $dest_height = 0;
840 if ((!$width) || (!$height)) {
844 if ($width > $max && $height > $max) {
845 // very tall image (greater than 16:9)
846 // constrain the width - let the height float.
848 if ((($height * 9) / 16) > $width) {
850 $dest_height = intval(($height * $max) / $width);
851 } elseif ($width > $height) {
852 // else constrain both dimensions
854 $dest_height = intval(($height * $max) / $width);
856 $dest_width = intval(($width * $max) / $height);
862 $dest_height = intval(($height * $max) / $width);
864 if ($height > $max) {
865 // very tall image (greater than 16:9)
866 // but width is OK - don't do anything
868 if ((($height * 9) / 16) > $width) {
869 $dest_width = $width;
870 $dest_height = $height;
872 $dest_width = intval(($width * $max) / $height);
876 $dest_width = $width;
877 $dest_height = $height;
881 return ["width" => $dest_width, "height" => $dest_height];
885 * @brief This function is used by the fromgplus addon
887 * @param integer $uid user id
888 * @param string $imagedata optional, default empty
889 * @param string $url optional, default empty
891 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
892 * @throws \ImagickException
894 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
897 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
898 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
902 if (!DBA::isResult($r)) {
903 Logger::log("Can't detect user data for uid ".$uid, Logger::DEBUG);
907 $page_owner_nick = $r[0]['nickname'];
910 /// $default_cid = $r[0]['id'];
911 /// $community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
913 if ((strlen($imagedata) == 0) && ($url == "")) {
914 Logger::log("No image data and no url provided", Logger::DEBUG);
916 } elseif (strlen($imagedata) == 0) {
917 Logger::log("Uploading picture from ".$url, Logger::DEBUG);
919 $stamp1 = microtime(true);
920 $imagedata = @file_get_contents($url);
921 $a->saveTimestamp($stamp1, "file");
924 $maximagesize = Config::get('system', 'maximagesize');
926 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
927 Logger::log("Image exceeds size limit of ".$maximagesize, Logger::DEBUG);
931 $tempfile = tempnam(get_temppath(), "cache");
933 $stamp1 = microtime(true);
934 file_put_contents($tempfile, $imagedata);
935 $a->saveTimestamp($stamp1, "file");
937 $data = getimagesize($tempfile);
939 if (!isset($data["mime"])) {
941 Logger::log("File is no picture", Logger::DEBUG);
945 $Image = new Image($imagedata, $data["mime"]);
947 if (!$Image->isValid()) {
949 Logger::log("Picture is no valid picture", Logger::DEBUG);
953 $Image->orient($tempfile);
956 $max_length = Config::get('system', 'max_image_length');
958 $max_length = MAX_IMAGE_LENGTH;
961 if ($max_length > 0) {
962 $Image->scaleDown($max_length);
965 $width = $Image->getWidth();
966 $height = $Image->getHeight();
968 $hash = Photo::newResource();
972 // Pictures are always public by now
973 //$defperm = '<'.$default_cid.'>';
977 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
980 Logger::log("Picture couldn't be stored", Logger::DEBUG);
984 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
985 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
987 if ($width > 800 || $height > 800) {
988 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
991 if ($width > 640 || $height > 640) {
992 $Image->scaleDown(640);
993 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
995 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
999 if ($width > 320 || $height > 320) {
1000 $Image->scaleDown(320);
1001 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
1003 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
1007 if ($width > 160 && $height > 160) {
1011 $min = $Image->getWidth();
1013 $x = ($min - 160) / 2;
1016 if ($Image->getHeight() < $min) {
1017 $min = $Image->getHeight();
1019 $y = ($min - 160) / 2;
1024 $Image->crop(160, $x, $y, $min, $min);
1026 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1028 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1032 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1033 $image["preview"] = $image["full"];
1035 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1036 //if (isset($image["thumb"]))
1037 // $image["preview"] = $image["thumb"];
1039 // Unsure, if this should be activated or deactivated
1040 //if (isset($image["small"]))
1041 // $image["preview"] = $image["small"];
1043 if (isset($image["medium"])) {
1044 $image["preview"] = $image["medium"];