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;
18 require_once "include/photos.php";
21 * Class to handle images
28 * Put back gd stuff, not everybody have Imagick
38 * @brief supported mimetypes and corresponding file extensions
41 public static function supportedTypes()
43 if (class_exists('Imagick')) {
44 // Imagick::queryFormats won't help us a lot there...
45 // At least, not yet, other parts of friendica uses this array
47 'image/jpeg' => 'jpg',
53 $t['image/jpeg'] ='jpg';
54 if (imagetypes() & IMG_PNG) {
55 $t['image/png'] = 'png';
64 * @param object $data data
65 * @param boolean $type optional, default null
68 public function __construct($data, $type = null)
70 $this->imagick = class_exists('Imagick');
71 $this->types = static::supportedTypes();
72 if (!array_key_exists($type, $this->types)) {
77 if ($this->isImagick() && $this->loadData($data)) {
80 // Failed to load with Imagick, fallback
81 $this->imagick = false;
83 return $this->loadData($data);
90 public function __destruct()
93 if ($this->isImagick()) {
94 $this->image->clear();
95 $this->image->destroy();
98 if (is_resource($this->image)) {
99 imagedestroy($this->image);
107 public function isImagick()
109 return $this->imagick;
113 * @brief Maps Mime types to Imagick formats
114 * @return array With with image formats (mime type as key)
116 public static function getFormatsMap()
119 'image/jpeg' => 'JPG',
120 'image/png' => 'PNG',
127 * @param object $data data
130 private function loadData($data)
132 if ($this->isImagick()) {
133 $this->image = new Imagick();
135 $this->image->readImageBlob($data);
136 } catch (Exception $e) {
137 // Imagick couldn't use the data
142 * Setup the image to the format it will be saved to
144 $map = self::getFormatsMap();
145 $format = $map[$type];
146 $this->image->setFormat($format);
148 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
149 $this->image = $this->image->coalesceImages();
152 * setup the compression here, so we'll do it only once
154 switch ($this->getType()) {
156 $quality = Config::get('system', 'png_quality');
157 if ((! $quality) || ($quality > 9)) {
158 $quality = PNG_QUALITY;
161 * From http://www.imagemagick.org/script/command-line-options.php#quality:
163 * 'For the MNG and PNG image formats, the quality value sets
164 * the zlib compression level (quality / 10) and filter-type (quality % 10).
165 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
166 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
168 $quality = $quality * 10;
169 $this->image->setCompressionQuality($quality);
172 $quality = Config::get('system', 'jpeg_quality');
173 if ((! $quality) || ($quality > 100)) {
174 $quality = JPEG_QUALITY;
176 $this->image->setCompressionQuality($quality);
179 // The 'width' and 'height' properties are only used by non-Imagick routines.
180 $this->width = $this->image->getImageWidth();
181 $this->height = $this->image->getImageHeight();
187 $this->valid = false;
188 $this->image = @imagecreatefromstring($data);
189 if ($this->image !== false) {
190 $this->width = imagesx($this->image);
191 $this->height = imagesy($this->image);
193 imagealphablending($this->image, false);
194 imagesavealpha($this->image, true);
205 public function isValid()
207 if ($this->isImagick()) {
208 return ($this->image !== false);
216 public function getWidth()
218 if (!$this->isValid()) {
222 if ($this->isImagick()) {
223 return $this->image->getImageWidth();
231 public function getHeight()
233 if (!$this->isValid()) {
237 if ($this->isImagick()) {
238 return $this->image->getImageHeight();
240 return $this->height;
246 public function getImage()
248 if (!$this->isValid()) {
252 if ($this->isImagick()) {
254 $this->image = $this->image->deconstructImages();
263 public function getType()
265 if (!$this->isValid()) {
275 public function getExt()
277 if (!$this->isValid()) {
281 return $this->types[$this->getType()];
285 * @param integer $max max dimension
288 public function scaleDown($max)
290 if (!$this->isValid()) {
294 $width = $this->getWidth();
295 $height = $this->getHeight();
297 $dest_width = $dest_height = 0;
299 if ((! $width)|| (! $height)) {
303 if ($width > $max && $height > $max) {
304 // very tall image (greater than 16:9)
305 // constrain the width - let the height float.
307 if ((($height * 9) / 16) > $width) {
309 $dest_height = intval(($height * $max) / $width);
310 } elseif ($width > $height) {
311 // else constrain both dimensions
313 $dest_height = intval(($height * $max) / $width);
315 $dest_width = intval(($width * $max) / $height);
321 $dest_height = intval(($height * $max) / $width);
323 if ($height > $max) {
324 // very tall image (greater than 16:9)
325 // but width is OK - don't do anything
327 if ((($height * 9) / 16) > $width) {
328 $dest_width = $width;
329 $dest_height = $height;
331 $dest_width = intval(($width * $max) / $height);
335 $dest_width = $width;
336 $dest_height = $height;
342 if ($this->isImagick()) {
344 * If it is not animated, there will be only one iteration here,
345 * so don't bother checking
347 // Don't forget to go back to the first frame
348 $this->image->setFirstIterator();
350 // FIXME - implement horizantal bias for scaling as in followin GD functions
351 // to allow very tall images to be constrained only horizontally.
353 $this->image->scaleImage($dest_width, $dest_height);
354 } while ($this->image->nextImage());
356 // These may not be necessary any more
357 $this->width = $this->image->getImageWidth();
358 $this->height = $this->image->getImageHeight();
364 $dest = imagecreatetruecolor($dest_width, $dest_height);
365 imagealphablending($dest, false);
366 imagesavealpha($dest, true);
367 if ($this->type=='image/png') {
368 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
370 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
372 imagedestroy($this->image);
374 $this->image = $dest;
375 $this->width = imagesx($this->image);
376 $this->height = imagesy($this->image);
380 * @param integer $degrees degrees to rotate image
383 public function rotate($degrees)
385 if (!$this->isValid()) {
389 if ($this->isImagick()) {
390 $this->image->setFirstIterator();
392 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
393 } while ($this->image->nextImage());
397 // if script dies at this point check memory_limit setting in php.ini
398 $this->image = imagerotate($this->image, $degrees, 0);
399 $this->width = imagesx($this->image);
400 $this->height = imagesy($this->image);
404 * @param boolean $horiz optional, default true
405 * @param boolean $vert optional, default false
408 public function flip($horiz = true, $vert = false)
410 if (!$this->isValid()) {
414 if ($this->isImagick()) {
415 $this->image->setFirstIterator();
418 $this->image->flipImage();
421 $this->image->flopImage();
423 } while ($this->image->nextImage());
427 $w = imagesx($this->image);
428 $h = imagesy($this->image);
429 $flipped = imagecreate($w, $h);
431 for ($x = 0; $x < $w; $x++) {
432 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
436 for ($y = 0; $y < $h; $y++) {
437 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
440 $this->image = $flipped;
444 * @param string $filename filename
447 public function orient($filename)
449 if ($this->isImagick()) {
450 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
451 $orientation = $this->image->getImageOrientation();
452 switch ($orientation) {
453 case Imagick::ORIENTATION_BOTTOMRIGHT:
454 $this->image->rotateimage("#000", 180);
456 case Imagick::ORIENTATION_RIGHTTOP:
457 $this->image->rotateimage("#000", 90);
459 case Imagick::ORIENTATION_LEFTBOTTOM:
460 $this->image->rotateimage("#000", -90);
464 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
467 // based off comment on http://php.net/manual/en/function.imagerotate.php
469 if (!$this->isValid()) {
473 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
477 $exif = @exif_read_data($filename, null, true);
482 $ort = $exif['IFD0']['Orientation'];
488 case 2: // horizontal flip
492 case 3: // 180 rotate left
496 case 4: // vertical flip
497 $this->flip(false, true);
500 case 5: // vertical flip + 90 rotate right
501 $this->flip(false, true);
505 case 6: // 90 rotate right
509 case 7: // horizontal flip + 90 rotate right
514 case 8: // 90 rotate left
519 // logger('exif: ' . print_r($exif,true));
524 * @param integer $min minimum dimension
527 public function scaleUp($min)
529 if (!$this->isValid()) {
533 $width = $this->getWidth();
534 $height = $this->getHeight();
536 $dest_width = $dest_height = 0;
538 if ((!$width)|| (!$height)) {
542 if ($width < $min && $height < $min) {
543 if ($width > $height) {
545 $dest_height = intval(($height * $min) / $width);
547 $dest_width = intval(($width * $min) / $height);
553 $dest_height = intval(($height * $min) / $width);
555 if ($height < $min) {
556 $dest_width = intval(($width * $min) / $height);
559 $dest_width = $width;
560 $dest_height = $height;
565 if ($this->isImagick()) {
566 return $this->scaleDown($dest_width, $dest_height);
569 $dest = imagecreatetruecolor($dest_width, $dest_height);
570 imagealphablending($dest, false);
571 imagesavealpha($dest, true);
572 if ($this->type=='image/png') {
573 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
575 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $width, $height);
577 imagedestroy($this->image);
579 $this->image = $dest;
580 $this->width = imagesx($this->image);
581 $this->height = imagesy($this->image);
585 * @param integer $dim dimension
588 public function scaleToSquare($dim)
590 if (!$this->isValid()) {
594 if ($this->isImagick()) {
595 $this->image->setFirstIterator();
597 $this->image->scaleImage($dim, $dim);
598 } while ($this->image->nextImage());
602 $dest = imagecreatetruecolor($dim, $dim);
603 imagealphablending($dest, false);
604 imagesavealpha($dest, true);
605 if ($this->type=='image/png') {
606 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
608 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dim, $dim, $this->width, $this->height);
610 imagedestroy($this->image);
612 $this->image = $dest;
613 $this->width = imagesx($this->image);
614 $this->height = imagesy($this->image);
618 * @param integer $max maximum
619 * @param integer $x x coordinate
620 * @param integer $y y coordinate
621 * @param integer $w width
622 * @param integer $h height
625 public function crop($max, $x, $y, $w, $h)
627 if (!$this->isValid()) {
631 if ($this->isImagick()) {
632 $this->image->setFirstIterator();
634 $this->image->cropImage($w, $h, $x, $y);
636 * We need to remove the canva,
637 * or the image is not resized to the crop:
638 * http://php.net/manual/en/imagick.cropimage.php#97232
640 $this->image->setImagePage(0, 0, 0, 0);
641 } while ($this->image->nextImage());
642 return $this->scaleDown($max);
645 $dest = imagecreatetruecolor($max, $max);
646 imagealphablending($dest, false);
647 imagesavealpha($dest, true);
648 if ($this->type=='image/png') {
649 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
651 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
653 imagedestroy($this->image);
655 $this->image = $dest;
656 $this->width = imagesx($this->image);
657 $this->height = imagesy($this->image);
661 * @param string $path file path
664 public function saveToFilePath($path)
666 if (!$this->isValid()) {
670 $string = $this->asString();
674 $stamp1 = microtime(true);
675 file_put_contents($path, $string);
676 $a->save_timestamp($stamp1, "file");
680 * @brief Magic method allowing string casting of an Image object
682 * Ex: $data = $Image->asString();
684 * $data = (string) $Image;
688 public function __toString() {
689 return $this->asString();
695 public function asString()
697 if (!$this->isValid()) {
701 if ($this->isImagick()) {
703 $this->image = $this->image->deconstructImages();
704 $string = $this->image->getImagesBlob();
712 // Enable interlacing
713 imageinterlace($this->image, true);
715 switch ($this->getType()) {
717 $quality = Config::get('system', 'png_quality');
718 if ((!$quality) || ($quality > 9)) {
719 $quality = PNG_QUALITY;
721 imagepng($this->image, null, $quality);
724 $quality = Config::get('system', 'jpeg_quality');
725 if ((!$quality) || ($quality > 100)) {
726 $quality = JPEG_QUALITY;
728 imagejpeg($this->image, null, $quality);
730 $string = ob_get_contents();
737 * Guess image mimetype from filename or from Content-Type header
739 * @param string $filename Image filename
740 * @param boolean $fromcurl Check Content-Type header from curl request
744 public static function guessType($filename, $fromcurl = false)
746 logger('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG);
751 $h = explode("\n", $a->get_curl_headers());
753 list($k,$v) = array_map("trim", explode(":", trim($l), 2));
756 if (array_key_exists('Content-Type', $headers))
757 $type = $headers['Content-Type'];
759 if (is_null($type)) {
760 // Guessing from extension? Isn't that... dangerous?
761 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
763 * Well, this not much better,
764 * but at least it comes from the data inside the image,
765 * we won't be tricked by a manipulated extension
767 $image = new Imagick($filename);
768 $type = $image->getImageMimeType();
769 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
771 $ext = pathinfo($filename, PATHINFO_EXTENSION);
772 $types = self::supportedTypes();
773 $type = "image/jpeg";
774 foreach ($types as $m => $e) {
781 logger('Image: guessType: type='.$type, LOGGER_DEBUG);
786 * @param string $url url
789 public static function getInfoFromURL($url)
793 $data = Cache::get($url);
795 if (is_null($data) || !$data || !is_array($data)) {
796 $img_str = fetch_url($url, true, $redirects, 4);
797 $filesize = strlen($img_str);
799 if (function_exists("getimagesizefromstring")) {
800 $data = getimagesizefromstring($img_str);
802 $tempfile = tempnam(get_temppath(), "cache");
805 $stamp1 = microtime(true);
806 file_put_contents($tempfile, $img_str);
807 $a->save_timestamp($stamp1, "file");
809 $data = getimagesize($tempfile);
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 $dest_width = $dest_height = 0;
833 if ((!$width) || (!$height)) {
837 if ($width > $max && $height > $max) {
838 // very tall image (greater than 16:9)
839 // constrain the width - let the height float.
841 if ((($height * 9) / 16) > $width) {
843 $dest_height = intval(($height * $max) / $width);
844 } elseif ($width > $height) {
845 // else constrain both dimensions
847 $dest_height = intval(($height * $max) / $width);
849 $dest_width = intval(($width * $max) / $height);
855 $dest_height = intval(($height * $max) / $width);
857 if ($height > $max) {
858 // very tall image (greater than 16:9)
859 // but width is OK - don't do anything
861 if ((($height * 9) / 16) > $width) {
862 $dest_width = $width;
863 $dest_height = $height;
865 $dest_width = intval(($width * $max) / $height);
869 $dest_width = $width;
870 $dest_height = $height;
874 return array("width" => $dest_width, "height" => $dest_height);
878 * @brief This function is used by the fromgplus addon
879 * @param object $a App
880 * @param integer $uid user id
881 * @param string $imagedata optional, default empty
882 * @param string $url optional, default empty
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 (!DBM::is_result($r)) {
894 logger("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'] == PAGE_COMMUNITY) ? true : false);
904 if ((strlen($imagedata) == 0) && ($url == "")) {
905 logger("No image data and no url provided", LOGGER_DEBUG);
907 } elseif (strlen($imagedata) == 0) {
908 logger("Uploading picture from ".$url, LOGGER_DEBUG);
910 $stamp1 = microtime(true);
911 $imagedata = @file_get_contents($url);
912 $a->save_timestamp($stamp1, "file");
915 $maximagesize = Config::get('system', 'maximagesize');
917 if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
918 logger("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->save_timestamp($stamp1, "file");
928 $data = getimagesize($tempfile);
930 if (!isset($data["mime"])) {
932 logger("File is no picture", LOGGER_DEBUG);
936 $Image = new Image($imagedata, $data["mime"]);
938 if (!$Image->isValid()) {
940 logger("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_new_resource();
963 // Pictures are always public by now
964 //$defperm = '<'.$default_cid.'>';
968 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 0, 0, $defperm);
971 logger("Picture couldn't be stored", LOGGER_DEBUG);
975 $image = array("page" => System::baseUrl().'/photos/'.$page_owner_nick.'/image/'.$hash,
976 "full" => System::baseUrl()."/photo/{$hash}-0.".$Image->getExt());
978 if ($width > 800 || $height > 800) {
979 $image["large"] = System::baseUrl()."/photo/{$hash}-0.".$Image->getExt();
982 if ($width > 640 || $height > 640) {
983 $Image->scaleDown(640);
984 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 1, 0, $defperm);
986 $image["medium"] = System::baseUrl()."/photo/{$hash}-1.".$Image->getExt();
990 if ($width > 320 || $height > 320) {
991 $Image->scaleDown(320);
992 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 2, 0, $defperm);
994 $image["small"] = System::baseUrl()."/photo/{$hash}-2.".$Image->getExt();
998 if ($width > 160 && $height > 160) {
1002 $min = $Image->getWidth();
1004 $x = ($min - 160) / 2;
1007 if ($Image->getHeight() < $min) {
1008 $min = $Image->getHeight();
1010 $y = ($min - 160) / 2;
1015 $Image->crop(160, $x, $y, $min, $min);
1017 $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, t('Wall Photos'), 3, 0, $defperm);
1019 $image["thumb"] = System::baseUrl()."/photo/{$hash}-3.".$Image->getExt();
1023 // Set the full image as preview image. This will be overwritten, if the picture is larger than 640.
1024 $image["preview"] = $image["full"];
1026 // Deactivated, since that would result in a cropped preview, if the picture wasn't larger than 320
1027 //if (isset($image["thumb"]))
1028 // $image["preview"] = $image["thumb"];
1030 // Unsure, if this should be activated or deactivated
1031 //if (isset($image["small"]))
1032 // $image["preview"] = $image["small"];
1034 if (isset($image["medium"])) {
1035 $image["preview"] = $image["medium"];