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
26 /** @var Imagick|resource */
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';
67 * @param boolean $type optional, default null
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69 * @throws \ImagickException
71 public function __construct($data, $type = null)
73 $this->imagick = class_exists('Imagick');
74 $this->types = static::supportedTypes();
75 if (!array_key_exists($type, $this->types)) {
80 if ($this->isImagick() && $this->loadData($data)) {
83 // Failed to load with Imagick, fallback
84 $this->imagick = false;
86 return $this->loadData($data);
93 public function __destruct()
96 if ($this->isImagick()) {
97 $this->image->clear();
98 $this->image->destroy();
101 if (is_resource($this->image)) {
102 imagedestroy($this->image);
110 public function isImagick()
112 return $this->imagick;
116 * @brief Maps Mime types to Imagick formats
117 * @return array With with image formats (mime type as key)
119 public static function getFormatsMap()
122 'image/jpeg' => 'JPG',
123 'image/png' => 'PNG',
130 * @param string $data data
132 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
133 * @throws \ImagickException
135 private function loadData($data)
137 if ($this->isImagick()) {
138 $this->image = new Imagick();
140 $this->image->readImageBlob($data);
141 } catch (Exception $e) {
142 // Imagick couldn't use the data
147 * Setup the image to the format it will be saved to
149 $map = self::getFormatsMap();
150 $format = $map[$this->type];
151 $this->image->setFormat($format);
153 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
154 $this->image = $this->image->coalesceImages();
157 * setup the compression here, so we'll do it only once
159 switch ($this->getType()) {
161 $quality = Config::get('system', 'png_quality');
162 if ((! $quality) || ($quality > 9)) {
163 $quality = PNG_QUALITY;
166 * From http://www.imagemagick.org/script/command-line-options.php#quality:
168 * 'For the MNG and PNG image formats, the quality value sets
169 * the zlib compression level (quality / 10) and filter-type (quality % 10).
170 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
171 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
173 $quality = $quality * 10;
174 $this->image->setCompressionQuality($quality);
177 $quality = Config::get('system', 'jpeg_quality');
178 if ((! $quality) || ($quality > 100)) {
179 $quality = JPEG_QUALITY;
181 $this->image->setCompressionQuality($quality);
184 // The 'width' and 'height' properties are only used by non-Imagick routines.
185 $this->width = $this->image->getImageWidth();
186 $this->height = $this->image->getImageHeight();
192 $this->valid = false;
193 $this->image = @imagecreatefromstring($data);
194 if ($this->image !== false) {
195 $this->width = imagesx($this->image);
196 $this->height = imagesy($this->image);
198 imagealphablending($this->image, false);
199 imagesavealpha($this->image, true);
210 public function isValid()
212 if ($this->isImagick()) {
213 return ($this->image !== false);
221 public function getWidth()
223 if (!$this->isValid()) {
227 if ($this->isImagick()) {
228 return $this->image->getImageWidth();
236 public function getHeight()
238 if (!$this->isValid()) {
242 if ($this->isImagick()) {
243 return $this->image->getImageHeight();
245 return $this->height;
251 public function getImage()
253 if (!$this->isValid()) {
257 if ($this->isImagick()) {
259 $this->image = $this->image->deconstructImages();
268 public function getType()
270 if (!$this->isValid()) {
280 public function getExt()
282 if (!$this->isValid()) {
286 return $this->types[$this->getType()];
290 * @param integer $max max dimension
293 public function scaleDown($max)
295 if (!$this->isValid()) {
299 $width = $this->getWidth();
300 $height = $this->getHeight();
302 if ((! $width)|| (! $height)) {
306 if ($width > $max && $height > $max) {
307 // very tall image (greater than 16:9)
308 // constrain the width - let the height float.
310 if ((($height * 9) / 16) > $width) {
312 $dest_height = intval(($height * $max) / $width);
313 } elseif ($width > $height) {
314 // else constrain both dimensions
316 $dest_height = intval(($height * $max) / $width);
318 $dest_width = intval(($width * $max) / $height);
324 $dest_height = intval(($height * $max) / $width);
326 if ($height > $max) {
327 // very tall image (greater than 16:9)
328 // but width is OK - don't do anything
330 if ((($height * 9) / 16) > $width) {
331 $dest_width = $width;
332 $dest_height = $height;
334 $dest_width = intval(($width * $max) / $height);
338 $dest_width = $width;
339 $dest_height = $height;
344 return $this->scale($dest_width, $dest_height);
348 * @param integer $degrees degrees to rotate image
351 public function rotate($degrees)
353 if (!$this->isValid()) {
357 if ($this->isImagick()) {
358 $this->image->setFirstIterator();
360 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
361 } while ($this->image->nextImage());
365 // if script dies at this point check memory_limit setting in php.ini
366 $this->image = imagerotate($this->image, $degrees, 0);
367 $this->width = imagesx($this->image);
368 $this->height = imagesy($this->image);
372 * @param boolean $horiz optional, default true
373 * @param boolean $vert optional, default false
376 public function flip($horiz = true, $vert = false)
378 if (!$this->isValid()) {
382 if ($this->isImagick()) {
383 $this->image->setFirstIterator();
386 $this->image->flipImage();
389 $this->image->flopImage();
391 } while ($this->image->nextImage());
395 $w = imagesx($this->image);
396 $h = imagesy($this->image);
397 $flipped = imagecreate($w, $h);
399 for ($x = 0; $x < $w; $x++) {
400 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
404 for ($y = 0; $y < $h; $y++) {
405 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
408 $this->image = $flipped;
412 * @param string $filename filename
415 public function orient($filename)
417 if ($this->isImagick()) {
418 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
419 $orientation = $this->image->getImageOrientation();
420 switch ($orientation) {
421 case Imagick::ORIENTATION_BOTTOMRIGHT:
422 $this->image->rotateimage("#000", 180);
424 case Imagick::ORIENTATION_RIGHTTOP:
425 $this->image->rotateimage("#000", 90);
427 case Imagick::ORIENTATION_LEFTBOTTOM:
428 $this->image->rotateimage("#000", -90);
432 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
435 // based off comment on http://php.net/manual/en/function.imagerotate.php
437 if (!$this->isValid()) {
441 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
445 $exif = @exif_read_data($filename, null, true);
450 $ort = $exif['IFD0']['Orientation'];
456 case 2: // horizontal flip
460 case 3: // 180 rotate left
464 case 4: // vertical flip
465 $this->flip(false, true);
468 case 5: // vertical flip + 90 rotate right
469 $this->flip(false, true);
473 case 6: // 90 rotate right
477 case 7: // horizontal flip + 90 rotate right
482 case 8: // 90 rotate left
487 // Logger::log('exif: ' . print_r($exif,true));
492 * @param integer $min minimum dimension
495 public function scaleUp($min)
497 if (!$this->isValid()) {
501 $width = $this->getWidth();
502 $height = $this->getHeight();
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
645 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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;
670 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
672 public function __toString() {
673 return $this->asString();
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
680 public function asString()
682 if (!$this->isValid()) {
686 if ($this->isImagick()) {
688 $this->image = $this->image->deconstructImages();
689 $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
727 * @throws \ImagickException
729 public static function guessType($filename, $fromcurl = false, $header = '')
731 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
775 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
777 public static function getInfoFromURL($url)
785 $data = Cache::get($url);
787 if (is_null($data) || !$data || !is_array($data)) {
788 $img_str = Network::fetchUrl($url, true, $redirects, 4);
794 $filesize = strlen($img_str);
797 if (function_exists("getimagesizefromstring")) {
798 $data = @getimagesizefromstring($img_str);
800 $tempfile = tempnam(get_temppath(), "cache");
803 $stamp1 = microtime(true);
804 file_put_contents($tempfile, $img_str);
805 $a->saveTimestamp($stamp1, "file");
807 $data = getimagesize($tempfile);
810 } catch (Exception $e) {
815 $data["size"] = $filesize;
818 Cache::set($url, $data);
825 * @param integer $width width
826 * @param integer $height height
827 * @param integer $max max
830 public static function getScalingDimensions($width, $height, $max)
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
879 * @param integer $uid user id
880 * @param string $imagedata optional, default empty
881 * @param string $url optional, default empty
883 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
884 * @throws \ImagickException
886 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
889 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
890 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
894 if (!DBA::isResult($r)) {
895 Logger::log("Can't detect user data for uid ".$uid, Logger::DEBUG);
899 $page_owner_nick = $r[0]['nickname'];
902 /// $default_cid = $r[0]['id'];
903 /// $community_page = (($r[0]['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
905 if ((strlen($imagedata) == 0) && ($url == "")) {
906 Logger::log("No image data and no url provided", Logger::DEBUG);
908 } elseif (strlen($imagedata) == 0) {
909 Logger::log("Uploading picture from ".$url, Logger::DEBUG);
911 $stamp1 = microtime(true);
912 $imagedata = @file_get_contents($url);
913 $a->saveTimestamp($stamp1, "file");
916 $maximagesize = Config::get('system', 'maximagesize');
918 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
919 Logger::log("Image exceeds size limit of ".$maximagesize, Logger::DEBUG);
923 $tempfile = tempnam(get_temppath(), "cache");
925 $stamp1 = microtime(true);
926 file_put_contents($tempfile, $imagedata);
927 $a->saveTimestamp($stamp1, "file");
929 $data = getimagesize($tempfile);
931 if (!isset($data["mime"])) {
933 Logger::log("File is no picture", Logger::DEBUG);
937 $Image = new Image($imagedata, $data["mime"]);
939 if (!$Image->isValid()) {
941 Logger::log("Picture is no valid picture", Logger::DEBUG);
945 $Image->orient($tempfile);
948 $max_length = Config::get('system', 'max_image_length');
950 $max_length = MAX_IMAGE_LENGTH;
953 if ($max_length > 0) {
954 $Image->scaleDown($max_length);
957 $width = $Image->getWidth();
958 $height = $Image->getHeight();
960 $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::log("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"];