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\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Photo;
19 * Class to handle images
26 * Put back gd stuff, not everybody have Imagick
36 * @brief supported mimetypes and corresponding file extensions
39 public static function supportedTypes()
41 if (class_exists('Imagick')) {
42 // Imagick::queryFormats won't help us a lot there...
43 // At least, not yet, other parts of friendica uses this array
45 'image/jpeg' => 'jpg',
51 $t['image/jpeg'] ='jpg';
52 if (imagetypes() & IMG_PNG) {
53 $t['image/png'] = 'png';
62 * @param object $data data
63 * @param boolean $type optional, default null
66 public function __construct($data, $type = null)
68 $this->imagick = class_exists('Imagick');
69 $this->types = static::supportedTypes();
70 if (!array_key_exists($type, $this->types)) {
75 if ($this->isImagick() && $this->loadData($data)) {
78 // Failed to load with Imagick, fallback
79 $this->imagick = false;
81 return $this->loadData($data);
88 public function __destruct()
91 if ($this->isImagick()) {
92 $this->image->clear();
93 $this->image->destroy();
96 if (is_resource($this->image)) {
97 imagedestroy($this->image);
105 public function isImagick()
107 return $this->imagick;
111 * @brief Maps Mime types to Imagick formats
112 * @return array With with image formats (mime type as key)
114 public static function getFormatsMap()
117 'image/jpeg' => 'JPG',
118 'image/png' => 'PNG',
125 * @param object $data data
128 private function loadData($data)
130 if ($this->isImagick()) {
131 $this->image = new Imagick();
133 $this->image->readImageBlob($data);
134 } catch (Exception $e) {
135 // Imagick couldn't use the data
140 * Setup the image to the format it will be saved to
142 $map = self::getFormatsMap();
143 $format = $map[$this->type];
144 $this->image->setFormat($format);
146 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
147 $this->image = $this->image->coalesceImages();
150 * setup the compression here, so we'll do it only once
152 switch ($this->getType()) {
154 $quality = Config::get('system', 'png_quality');
155 if ((! $quality) || ($quality > 9)) {
156 $quality = PNG_QUALITY;
159 * From http://www.imagemagick.org/script/command-line-options.php#quality:
161 * 'For the MNG and PNG image formats, the quality value sets
162 * the zlib compression level (quality / 10) and filter-type (quality % 10).
163 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
164 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
166 $quality = $quality * 10;
167 $this->image->setCompressionQuality($quality);
170 $quality = Config::get('system', 'jpeg_quality');
171 if ((! $quality) || ($quality > 100)) {
172 $quality = JPEG_QUALITY;
174 $this->image->setCompressionQuality($quality);
177 // The 'width' and 'height' properties are only used by non-Imagick routines.
178 $this->width = $this->image->getImageWidth();
179 $this->height = $this->image->getImageHeight();
185 $this->valid = false;
186 $this->image = @imagecreatefromstring($data);
187 if ($this->image !== false) {
188 $this->width = imagesx($this->image);
189 $this->height = imagesy($this->image);
191 imagealphablending($this->image, false);
192 imagesavealpha($this->image, true);
203 public function isValid()
205 if ($this->isImagick()) {
206 return ($this->image !== false);
214 public function getWidth()
216 if (!$this->isValid()) {
220 if ($this->isImagick()) {
221 return $this->image->getImageWidth();
229 public function getHeight()
231 if (!$this->isValid()) {
235 if ($this->isImagick()) {
236 return $this->image->getImageHeight();
238 return $this->height;
244 public function getImage()
246 if (!$this->isValid()) {
250 if ($this->isImagick()) {
252 $this->image = $this->image->deconstructImages();
261 public function getType()
263 if (!$this->isValid()) {
273 public function getExt()
275 if (!$this->isValid()) {
279 return $this->types[$this->getType()];
283 * @param integer $max max dimension
286 public function scaleDown($max)
288 if (!$this->isValid()) {
292 $width = $this->getWidth();
293 $height = $this->getHeight();
295 $dest_width = $dest_height = 0;
297 if ((! $width)|| (! $height)) {
301 if ($width > $max && $height > $max) {
302 // very tall image (greater than 16:9)
303 // constrain the width - let the height float.
305 if ((($height * 9) / 16) > $width) {
307 $dest_height = intval(($height * $max) / $width);
308 } elseif ($width > $height) {
309 // else constrain both dimensions
311 $dest_height = intval(($height * $max) / $width);
313 $dest_width = intval(($width * $max) / $height);
319 $dest_height = intval(($height * $max) / $width);
321 if ($height > $max) {
322 // very tall image (greater than 16:9)
323 // but width is OK - don't do anything
325 if ((($height * 9) / 16) > $width) {
326 $dest_width = $width;
327 $dest_height = $height;
329 $dest_width = intval(($width * $max) / $height);
333 $dest_width = $width;
334 $dest_height = $height;
339 return $this->scale($dest_width, $dest_height);
343 * @param integer $degrees degrees to rotate image
346 public function rotate($degrees)
348 if (!$this->isValid()) {
352 if ($this->isImagick()) {
353 $this->image->setFirstIterator();
355 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
356 } while ($this->image->nextImage());
360 // if script dies at this point check memory_limit setting in php.ini
361 $this->image = imagerotate($this->image, $degrees, 0);
362 $this->width = imagesx($this->image);
363 $this->height = imagesy($this->image);
367 * @param boolean $horiz optional, default true
368 * @param boolean $vert optional, default false
371 public function flip($horiz = true, $vert = false)
373 if (!$this->isValid()) {
377 if ($this->isImagick()) {
378 $this->image->setFirstIterator();
381 $this->image->flipImage();
384 $this->image->flopImage();
386 } while ($this->image->nextImage());
390 $w = imagesx($this->image);
391 $h = imagesy($this->image);
392 $flipped = imagecreate($w, $h);
394 for ($x = 0; $x < $w; $x++) {
395 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
399 for ($y = 0; $y < $h; $y++) {
400 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
403 $this->image = $flipped;
407 * @param string $filename filename
410 public function orient($filename)
412 if ($this->isImagick()) {
413 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
414 $orientation = $this->image->getImageOrientation();
415 switch ($orientation) {
416 case Imagick::ORIENTATION_BOTTOMRIGHT:
417 $this->image->rotateimage("#000", 180);
419 case Imagick::ORIENTATION_RIGHTTOP:
420 $this->image->rotateimage("#000", 90);
422 case Imagick::ORIENTATION_LEFTBOTTOM:
423 $this->image->rotateimage("#000", -90);
427 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
430 // based off comment on http://php.net/manual/en/function.imagerotate.php
432 if (!$this->isValid()) {
436 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
440 $exif = @exif_read_data($filename, null, true);
445 $ort = $exif['IFD0']['Orientation'];
451 case 2: // horizontal flip
455 case 3: // 180 rotate left
459 case 4: // vertical flip
460 $this->flip(false, true);
463 case 5: // vertical flip + 90 rotate right
464 $this->flip(false, true);
468 case 6: // 90 rotate right
472 case 7: // horizontal flip + 90 rotate right
477 case 8: // 90 rotate left
482 // logger('exif: ' . print_r($exif,true));
487 * @param integer $min minimum dimension
490 public function scaleUp($min)
492 if (!$this->isValid()) {
496 $width = $this->getWidth();
497 $height = $this->getHeight();
499 $dest_width = $dest_height = 0;
501 if ((!$width)|| (!$height)) {
505 if ($width < $min && $height < $min) {
506 if ($width > $height) {
508 $dest_height = intval(($height * $min) / $width);
510 $dest_width = intval(($width * $min) / $height);
516 $dest_height = intval(($height * $min) / $width);
518 if ($height < $min) {
519 $dest_width = intval(($width * $min) / $height);
522 $dest_width = $width;
523 $dest_height = $height;
528 return $this->scale($dest_width, $dest_height);
532 * @param integer $dim dimension
535 public function scaleToSquare($dim)
537 if (!$this->isValid()) {
541 return $this->scale($dim, $dim);
545 * @brief Scale image to target dimensions
547 * @param int $dest_width
548 * @param int $dest_height
551 private function scale($dest_width, $dest_height)
553 if (!$this->isValid()) {
557 if ($this->isImagick()) {
559 * If it is not animated, there will be only one iteration here,
560 * so don't bother checking
562 // Don't forget to go back to the first frame
563 $this->image->setFirstIterator();
565 // FIXME - implement horizontal bias for scaling as in following GD functions
566 // to allow very tall images to be constrained only horizontally.
567 $this->image->scaleImage($dest_width, $dest_height);
568 } while ($this->image->nextImage());
570 // These may not be necessary anymore
571 $this->width = $this->image->getImageWidth();
572 $this->height = $this->image->getImageHeight();
574 $dest = imagecreatetruecolor($dest_width, $dest_height);
575 imagealphablending($dest, false);
576 imagesavealpha($dest, true);
578 if ($this->type=='image/png') {
579 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
582 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
585 imagedestroy($this->image);
588 $this->image = $dest;
589 $this->width = imagesx($this->image);
590 $this->height = imagesy($this->image);
597 * @param integer $max maximum
598 * @param integer $x x coordinate
599 * @param integer $y y coordinate
600 * @param integer $w width
601 * @param integer $h height
604 public function crop($max, $x, $y, $w, $h)
606 if (!$this->isValid()) {
610 if ($this->isImagick()) {
611 $this->image->setFirstIterator();
613 $this->image->cropImage($w, $h, $x, $y);
615 * We need to remove the canva,
616 * or the image is not resized to the crop:
617 * http://php.net/manual/en/imagick.cropimage.php#97232
619 $this->image->setImagePage(0, 0, 0, 0);
620 } while ($this->image->nextImage());
621 return $this->scaleDown($max);
624 $dest = imagecreatetruecolor($max, $max);
625 imagealphablending($dest, false);
626 imagesavealpha($dest, true);
627 if ($this->type=='image/png') {
628 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
630 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
632 imagedestroy($this->image);
634 $this->image = $dest;
635 $this->width = imagesx($this->image);
636 $this->height = imagesy($this->image);
640 * @param string $path file path
643 public function saveToFilePath($path)
645 if (!$this->isValid()) {
649 $string = $this->asString();
653 $stamp1 = microtime(true);
654 file_put_contents($path, $string);
655 $a->save_timestamp($stamp1, "file");
659 * @brief Magic method allowing string casting of an Image object
661 * Ex: $data = $Image->asString();
663 * $data = (string) $Image;
667 public function __toString() {
668 return $this->asString();
674 public function asString()
676 if (!$this->isValid()) {
680 if ($this->isImagick()) {
682 $this->image = $this->image->deconstructImages();
683 $string = $this->image->getImagesBlob();
691 // Enable interlacing
692 imageinterlace($this->image, true);
694 switch ($this->getType()) {
696 $quality = Config::get('system', 'png_quality');
697 if ((!$quality) || ($quality > 9)) {
698 $quality = PNG_QUALITY;
700 imagepng($this->image, null, $quality);
703 $quality = Config::get('system', 'jpeg_quality');
704 if ((!$quality) || ($quality > 100)) {
705 $quality = JPEG_QUALITY;
707 imagejpeg($this->image, null, $quality);
709 $string = ob_get_contents();
716 * Guess image mimetype from filename or from Content-Type header
718 * @param string $filename Image filename
719 * @param boolean $fromcurl Check Content-Type header from curl request
723 public static function guessType($filename, $fromcurl = false)
725 logger('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
730 $h = explode("\n", $a->get_curl_headers());
732 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
735 if (array_key_exists('Content-Type', $headers))
736 $type = $headers['Content-Type'];
738 if (is_null($type)) {
739 // Guessing from extension? Isn't that... dangerous?
740 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
742 * Well, this not much better,
743 * but at least it comes from the data inside the image,
744 * we won't be tricked by a manipulated extension
746 $image = new Imagick($filename);
747 $type = $image->getImageMimeType();
748 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
750 $ext = pathinfo($filename, PATHINFO_EXTENSION);
751 $types = self::supportedTypes();
752 $type = "image/jpeg";
753 foreach ($types as $m => $e) {
760 logger('Image: guessType: type='.$type, LOGGER_DEBUG);
765 * @param string $url url
768 public static function getInfoFromURL($url)
772 $data = Cache::get($url);
774 if (is_null($data) || !$data || !is_array($data)) {
775 $img_str = fetch_url($url, true, $redirects, 4);
776 $filesize = strlen($img_str);
778 if (function_exists("getimagesizefromstring")) {
779 $data = getimagesizefromstring($img_str);
781 $tempfile = tempnam(get_temppath(), "cache");
784 $stamp1 = microtime(true);
785 file_put_contents($tempfile, $img_str);
786 $a->save_timestamp($stamp1, "file");
788 $data = getimagesize($tempfile);
793 $data["size"] = $filesize;
796 Cache::set($url, $data);
803 * @param integer $width width
804 * @param integer $height height
805 * @param integer $max max
808 public static function getScalingDimensions($width, $height, $max)
810 $dest_width = $dest_height = 0;
812 if ((!$width) || (!$height)) {
816 if ($width > $max && $height > $max) {
817 // very tall image (greater than 16:9)
818 // constrain the width - let the height float.
820 if ((($height * 9) / 16) > $width) {
822 $dest_height = intval(($height * $max) / $width);
823 } elseif ($width > $height) {
824 // else constrain both dimensions
826 $dest_height = intval(($height * $max) / $width);
828 $dest_width = intval(($width * $max) / $height);
834 $dest_height = intval(($height * $max) / $width);
836 if ($height > $max) {
837 // very tall image (greater than 16:9)
838 // but width is OK - don't do anything
840 if ((($height * 9) / 16) > $width) {
841 $dest_width = $width;
842 $dest_height = $height;
844 $dest_width = intval(($width * $max) / $height);
848 $dest_width = $width;
849 $dest_height = $height;
853 return array("width" => $dest_width, "height" => $dest_height);
857 * @brief This function is used by the fromgplus addon
858 * @param object $a App
859 * @param integer $uid user id
860 * @param string $imagedata optional, default empty
861 * @param string $url optional, default empty
864 public static function storePhoto(App $a, $uid, $imagedata = "", $url = "")
867 "SELECT `user`.`nickname`, `user`.`page-flags`, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`
868 WHERE `user`.`uid` = %d AND `user`.`blocked` = 0 AND `contact`.`self` = 1 LIMIT 1",
872 if (!DBM::is_result($r)) {
873 logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG);
877 $page_owner_nick = $r[0]['nickname'];
880 /// $default_cid = $r[0]['id'];
881 /// $community_page = (($r[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
883 if ((strlen($imagedata) == 0) && ($url == "")) {
884 logger("No image data and no url provided", LOGGER_DEBUG);
886 } elseif (strlen($imagedata) == 0) {
887 logger("Uploading picture from ".$url, LOGGER_DEBUG);
889 $stamp1 = microtime(true);
890 $imagedata = @file_get_contents($url);
891 $a->save_timestamp($stamp1, "file");
894 $maximagesize = Config::get('system', 'maximagesize');
896 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
897 logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG);
901 $tempfile = tempnam(get_temppath(), "cache");
903 $stamp1 = microtime(true);
904 file_put_contents($tempfile, $imagedata);
905 $a->save_timestamp($stamp1, "file");
907 $data = getimagesize($tempfile);
909 if (!isset($data["mime"])) {
911 logger("File is no picture", LOGGER_DEBUG);
915 $Image = new Image($imagedata, $data["mime"]);
917 if (!$Image->isValid()) {
919 logger("Picture is no valid picture", LOGGER_DEBUG);
923 $Image->orient($tempfile);
926 $max_length = Config::get('system', 'max_image_length');
928 $max_length = MAX_IMAGE_LENGTH;
931 if ($max_length > 0) {
932 $Image->scaleDown($max_length);
935 $width = $Image->getWidth();
936 $height = $Image->getHeight();
938 $hash = photo_new_resource();
942 // Pictures are always public by now
943 //$defperm = '<'.$default_cid.'>';
947 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
950 logger("Picture couldn't be stored", LOGGER_DEBUG);
954 $image = array("page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
955 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt());
957 if ($width > 800 || $height > 800) {
958 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
961 if ($width > 640 || $height > 640) {
962 $Image->scaleDown(640);
963 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
965 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
969 if ($width > 320 || $height > 320) {
970 $Image->scaleDown(320);
971 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
973 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
977 if ($width > 160 && $height > 160) {
981 $min = $Image->getWidth();
983 $x = ($min - 160) / 2;
986 if ($Image->getHeight() < $min) {
987 $min = $Image->getHeight();
989 $y = ($min - 160) / 2;
994 $Image->crop(160, $x, $y, $min, $min);
996 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
998 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1002 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1003 $image["preview"] = $image["full"];
1005 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1006 //if (isset($image["thumb"]))
1007 // $image["preview"] = $image["thumb"];
1009 // Unsure, if this should be activated or deactivated
1010 //if (isset($image["small"]))
1011 // $image["preview"] = $image["small"];
1013 if (isset($image["medium"])) {
1014 $image["preview"] = $image["medium"];