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
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 object $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 $dest_width = $dest_height = 0;
304 if ((! $width)|| (! $height)) {
308 if ($width > $max && $height > $max) {
309 // very tall image (greater than 16:9)
310 // constrain the width - let the height float.
312 if ((($height * 9) / 16) > $width) {
314 $dest_height = intval(($height * $max) / $width);
315 } elseif ($width > $height) {
316 // else constrain both dimensions
318 $dest_height = intval(($height * $max) / $width);
320 $dest_width = intval(($width * $max) / $height);
326 $dest_height = intval(($height * $max) / $width);
328 if ($height > $max) {
329 // very tall image (greater than 16:9)
330 // but width is OK - don't do anything
332 if ((($height * 9) / 16) > $width) {
333 $dest_width = $width;
334 $dest_height = $height;
336 $dest_width = intval(($width * $max) / $height);
340 $dest_width = $width;
341 $dest_height = $height;
346 return $this->scale($dest_width, $dest_height);
350 * @param integer $degrees degrees to rotate image
353 public function rotate($degrees)
355 if (!$this->isValid()) {
359 if ($this->isImagick()) {
360 $this->image->setFirstIterator();
362 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
363 } while ($this->image->nextImage());
367 // if script dies at this point check memory_limit setting in php.ini
368 $this->image = imagerotate($this->image, $degrees, 0);
369 $this->width = imagesx($this->image);
370 $this->height = imagesy($this->image);
374 * @param boolean $horiz optional, default true
375 * @param boolean $vert optional, default false
378 public function flip($horiz = true, $vert = false)
380 if (!$this->isValid()) {
384 if ($this->isImagick()) {
385 $this->image->setFirstIterator();
388 $this->image->flipImage();
391 $this->image->flopImage();
393 } while ($this->image->nextImage());
397 $w = imagesx($this->image);
398 $h = imagesy($this->image);
399 $flipped = imagecreate($w, $h);
401 for ($x = 0; $x < $w; $x++) {
402 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
406 for ($y = 0; $y < $h; $y++) {
407 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
410 $this->image = $flipped;
414 * @param string $filename filename
417 public function orient($filename)
419 if ($this->isImagick()) {
420 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
421 $orientation = $this->image->getImageOrientation();
422 switch ($orientation) {
423 case Imagick::ORIENTATION_BOTTOMRIGHT:
424 $this->image->rotateimage("#000", 180);
426 case Imagick::ORIENTATION_RIGHTTOP:
427 $this->image->rotateimage("#000", 90);
429 case Imagick::ORIENTATION_LEFTBOTTOM:
430 $this->image->rotateimage("#000", -90);
434 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
437 // based off comment on http://php.net/manual/en/function.imagerotate.php
439 if (!$this->isValid()) {
443 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
447 $exif = @exif_read_data($filename, null, true);
452 $ort = $exif['IFD0']['Orientation'];
458 case 2: // horizontal flip
462 case 3: // 180 rotate left
466 case 4: // vertical flip
467 $this->flip(false, true);
470 case 5: // vertical flip + 90 rotate right
471 $this->flip(false, true);
475 case 6: // 90 rotate right
479 case 7: // horizontal flip + 90 rotate right
484 case 8: // 90 rotate left
489 // Logger::log('exif: ' . print_r($exif,true));
494 * @param integer $min minimum dimension
497 public function scaleUp($min)
499 if (!$this->isValid()) {
503 $width = $this->getWidth();
504 $height = $this->getHeight();
506 $dest_width = $dest_height = 0;
508 if ((!$width)|| (!$height)) {
512 if ($width < $min && $height < $min) {
513 if ($width > $height) {
515 $dest_height = intval(($height * $min) / $width);
517 $dest_width = intval(($width * $min) / $height);
523 $dest_height = intval(($height * $min) / $width);
525 if ($height < $min) {
526 $dest_width = intval(($width * $min) / $height);
529 $dest_width = $width;
530 $dest_height = $height;
535 return $this->scale($dest_width, $dest_height);
539 * @param integer $dim dimension
542 public function scaleToSquare($dim)
544 if (!$this->isValid()) {
548 return $this->scale($dim, $dim);
552 * @brief Scale image to target dimensions
554 * @param int $dest_width
555 * @param int $dest_height
558 private function scale($dest_width, $dest_height)
560 if (!$this->isValid()) {
564 if ($this->isImagick()) {
566 * If it is not animated, there will be only one iteration here,
567 * so don't bother checking
569 // Don't forget to go back to the first frame
570 $this->image->setFirstIterator();
572 // FIXME - implement horizontal bias for scaling as in following GD functions
573 // to allow very tall images to be constrained only horizontally.
574 $this->image->scaleImage($dest_width, $dest_height);
575 } while ($this->image->nextImage());
577 // These may not be necessary anymore
578 $this->width = $this->image->getImageWidth();
579 $this->height = $this->image->getImageHeight();
581 $dest = imagecreatetruecolor($dest_width, $dest_height);
582 imagealphablending($dest, false);
583 imagesavealpha($dest, true);
585 if ($this->type=='image/png') {
586 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
589 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
592 imagedestroy($this->image);
595 $this->image = $dest;
596 $this->width = imagesx($this->image);
597 $this->height = imagesy($this->image);
604 * @param integer $max maximum
605 * @param integer $x x coordinate
606 * @param integer $y y coordinate
607 * @param integer $w width
608 * @param integer $h height
611 public function crop($max, $x, $y, $w, $h)
613 if (!$this->isValid()) {
617 if ($this->isImagick()) {
618 $this->image->setFirstIterator();
620 $this->image->cropImage($w, $h, $x, $y);
622 * We need to remove the canva,
623 * or the image is not resized to the crop:
624 * http://php.net/manual/en/imagick.cropimage.php#97232
626 $this->image->setImagePage(0, 0, 0, 0);
627 } while ($this->image->nextImage());
628 return $this->scaleDown($max);
631 $dest = imagecreatetruecolor($max, $max);
632 imagealphablending($dest, false);
633 imagesavealpha($dest, true);
634 if ($this->type=='image/png') {
635 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
637 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
639 imagedestroy($this->image);
641 $this->image = $dest;
642 $this->width = imagesx($this->image);
643 $this->height = imagesy($this->image);
647 * @param string $path file path
649 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
651 public function saveToFilePath($path)
653 if (!$this->isValid()) {
657 $string = $this->asString();
661 $stamp1 = microtime(true);
662 file_put_contents($path, $string);
663 $a->saveTimestamp($stamp1, "file");
667 * @brief Magic method allowing string casting of an Image object
669 * Ex: $data = $Image->asString();
671 * $data = (string) $Image;
674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
676 public function __toString() {
677 return $this->asString();
682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684 public function asString()
686 if (!$this->isValid()) {
690 if ($this->isImagick()) {
692 $this->image = $this->image->deconstructImages();
693 $string = $this->image->getImagesBlob();
701 // Enable interlacing
702 imageinterlace($this->image, true);
704 switch ($this->getType()) {
706 $quality = Config::get('system', 'png_quality');
707 if ((!$quality) || ($quality > 9)) {
708 $quality = PNG_QUALITY;
710 imagepng($this->image, null, $quality);
713 $quality = Config::get('system', 'jpeg_quality');
714 if ((!$quality) || ($quality > 100)) {
715 $quality = JPEG_QUALITY;
717 imagejpeg($this->image, null, $quality);
719 $string = ob_get_contents();
726 * Guess image mimetype from filename or from Content-Type header
728 * @param string $filename Image filename
729 * @param boolean $fromcurl Check Content-Type header from curl request
730 * @param string $header passed headers to take into account
733 * @throws \ImagickException
735 public static function guessType($filename, $fromcurl = false, $header = '')
737 Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
742 $h = explode("\n", $header);
744 $data = array_map("trim", explode(":", trim($l), 2));
745 if (count($data) > 1) {
750 if (array_key_exists('Content-Type', $headers))
751 $type = $headers['Content-Type'];
753 if (is_null($type)) {
754 // Guessing from extension? Isn't that... dangerous?
755 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
757 * Well, this not much better,
758 * but at least it comes from the data inside the image,
759 * we won't be tricked by a manipulated extension
761 $image = new Imagick($filename);
762 $type = $image->getImageMimeType();
763 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
765 $ext = pathinfo($filename, PATHINFO_EXTENSION);
766 $types = self::supportedTypes();
767 $type = "image/jpeg";
768 foreach ($types as $m => $e) {
775 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
780 * @param string $url url
782 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
784 public static function getInfoFromURL($url)
792 $data = Cache::get($url);
794 if (is_null($data) || !$data || !is_array($data)) {
795 $img_str = Network::fetchUrl($url, true, $redirects, 4);
801 $filesize = strlen($img_str);
804 if (function_exists("getimagesizefromstring")) {
805 $data = @getimagesizefromstring($img_str);
807 $tempfile = tempnam(get_temppath(), "cache");
810 $stamp1 = microtime(true);
811 file_put_contents($tempfile, $img_str);
812 $a->saveTimestamp($stamp1, "file");
814 $data = getimagesize($tempfile);
817 } catch (Exception $e) {
822 $data["size"] = $filesize;
825 Cache::set($url, $data);
832 * @param integer $width width
833 * @param integer $height height
834 * @param integer $max max
837 public static function getScalingDimensions($width, $height, $max)
839 $dest_width = $dest_height = 0;
841 if ((!$width) || (!$height)) {
845 if ($width > $max && $height > $max) {
846 // very tall image (greater than 16:9)
847 // constrain the width - let the height float.
849 if ((($height * 9) / 16) > $width) {
851 $dest_height = intval(($height * $max) / $width);
852 } elseif ($width > $height) {
853 // else constrain both dimensions
855 $dest_height = intval(($height * $max) / $width);
857 $dest_width = intval(($width * $max) / $height);
863 $dest_height = intval(($height * $max) / $width);
865 if ($height > $max) {
866 // very tall image (greater than 16:9)
867 // but width is OK - don't do anything
869 if ((($height * 9) / 16) > $width) {
870 $dest_width = $width;
871 $dest_height = $height;
873 $dest_width = intval(($width * $max) / $height);
877 $dest_width = $width;
878 $dest_height = $height;
882 return ["width" => $dest_width, "height" => $dest_height];
886 * @brief This function is used by the fromgplus addon
888 * @param integer $uid user id
889 * @param string $imagedata optional, default empty
890 * @param string $url optional, default empty
892 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893 * @throws \ImagickException
895 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
898 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
899 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
903 if (!DBA::isResult($r)) {
904 Logger::log("Can't detect user data for uid ".$uid, Logger::DEBUG);
908 $page_owner_nick = $r[0]['nickname'];
911 /// $default_cid = $r[0]['id'];
912 /// $community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
914 if ((strlen($imagedata) == 0) && ($url == "")) {
915 Logger::log("No image data and no url provided", Logger::DEBUG);
917 } elseif (strlen($imagedata) == 0) {
918 Logger::log("Uploading picture from ".$url, Logger::DEBUG);
920 $stamp1 = microtime(true);
921 $imagedata = @file_get_contents($url);
922 $a->saveTimestamp($stamp1, "file");
925 $maximagesize = Config::get('system', 'maximagesize');
927 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
928 Logger::log("Image exceeds size limit of ".$maximagesize, Logger::DEBUG);
932 $tempfile = tempnam(get_temppath(), "cache");
934 $stamp1 = microtime(true);
935 file_put_contents($tempfile, $imagedata);
936 $a->saveTimestamp($stamp1, "file");
938 $data = getimagesize($tempfile);
940 if (!isset($data["mime"])) {
942 Logger::log("File is no picture", Logger::DEBUG);
946 $Image = new Image($imagedata, $data["mime"]);
948 if (!$Image->isValid()) {
950 Logger::log("Picture is no valid picture", Logger::DEBUG);
954 $Image->orient($tempfile);
957 $max_length = Config::get('system', 'max_image_length');
959 $max_length = MAX_IMAGE_LENGTH;
962 if ($max_length > 0) {
963 $Image->scaleDown($max_length);
966 $width = $Image->getWidth();
967 $height = $Image->getHeight();
969 $hash = Photo::newResource();
973 // Pictures are always public by now
974 //$defperm = '<'.$default_cid.'>';
978 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
981 Logger::log("Picture couldn't be stored", Logger::DEBUG);
985 $image = ["page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
986 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt()];
988 if ($width > 800 || $height > 800) {
989 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
992 if ($width > 640 || $height > 640) {
993 $Image->scaleDown(640);
994 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 1, 0, $defperm);
996 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
1000 if ($width > 320 || $height > 320) {
1001 $Image->scaleDown(320);
1002 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 2, 0, $defperm);
1004 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
1008 if ($width > 160 && $height > 160) {
1012 $min = $Image->getWidth();
1014 $x = ($min - 160) / 2;
1017 if ($Image->getHeight() < $min) {
1018 $min = $Image->getHeight();
1020 $y = ($min - 160) / 2;
1025 $Image->crop(160, $x, $y, $min, $min);
1027 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 3, 0, $defperm);
1029 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1033 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1034 $image["preview"] = $image["full"];
1036 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1037 //if (isset($image["thumb"]))
1038 // $image["preview"] = $image["thumb"];
1040 // Unsure, if this should be activated or deactivated
1041 //if (isset($image["small"]))
1042 // $image["preview"] = $image["small"];
1044 if (isset($image["medium"])) {
1045 $image["preview"] = $image["medium"];