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\Logger;
12 use Friendica\Core\System;
13 use Friendica\Util\Network;
18 * Class to handle images
22 /** @var Imagick|resource */
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';
63 * @param boolean $type optional, default null
64 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
65 * @throws \ImagickException
67 public function __construct($data, $type = null)
69 $this->imagick = class_exists('Imagick');
70 $this->types = static::supportedTypes();
71 if (!array_key_exists($type, $this->types)) {
76 if ($this->isImagick() && $this->loadData($data)) {
79 // Failed to load with Imagick, fallback
80 $this->imagick = false;
82 return $this->loadData($data);
89 public function __destruct()
92 if ($this->isImagick()) {
93 $this->image->clear();
94 $this->image->destroy();
97 if (is_resource($this->image)) {
98 imagedestroy($this->image);
106 public function isImagick()
108 return $this->imagick;
112 * @brief Maps Mime types to Imagick formats
113 * @return array With with image formats (mime type as key)
115 public static function getFormatsMap()
118 'image/jpeg' => 'JPG',
119 'image/png' => 'PNG',
126 * @param string $data data
128 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 * @throws \ImagickException
131 private function loadData($data)
133 if ($this->isImagick()) {
134 $this->image = new Imagick();
136 $this->image->readImageBlob($data);
137 } catch (Exception $e) {
138 // Imagick couldn't use the data
143 * Setup the image to the format it will be saved to
145 $map = self::getFormatsMap();
146 $format = $map[$this->type];
147 $this->image->setFormat($format);
149 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
150 $this->image = $this->image->coalesceImages();
153 * setup the compression here, so we'll do it only once
155 switch ($this->getType()) {
157 $quality = Config::get('system', 'png_quality');
158 if ((! $quality) || ($quality > 9)) {
159 $quality = PNG_QUALITY;
162 * From http://www.imagemagick.org/script/command-line-options.php#quality:
164 * 'For the MNG and PNG image formats, the quality value sets
165 * the zlib compression level (quality / 10) and filter-type (quality % 10).
166 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
167 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
169 $quality = $quality * 10;
170 $this->image->setCompressionQuality($quality);
173 $quality = Config::get('system', 'jpeg_quality');
174 if ((! $quality) || ($quality > 100)) {
175 $quality = JPEG_QUALITY;
177 $this->image->setCompressionQuality($quality);
180 // The 'width' and 'height' properties are only used by non-Imagick routines.
181 $this->width = $this->image->getImageWidth();
182 $this->height = $this->image->getImageHeight();
188 $this->valid = false;
189 $this->image = @imagecreatefromstring($data);
190 if ($this->image !== false) {
191 $this->width = imagesx($this->image);
192 $this->height = imagesy($this->image);
194 imagealphablending($this->image, false);
195 imagesavealpha($this->image, true);
206 public function isValid()
208 if ($this->isImagick()) {
209 return ($this->image !== false);
217 public function getWidth()
219 if (!$this->isValid()) {
223 if ($this->isImagick()) {
224 return $this->image->getImageWidth();
232 public function getHeight()
234 if (!$this->isValid()) {
238 if ($this->isImagick()) {
239 return $this->image->getImageHeight();
241 return $this->height;
247 public function getImage()
249 if (!$this->isValid()) {
253 if ($this->isImagick()) {
255 $this->image = $this->image->deconstructImages();
264 public function getType()
266 if (!$this->isValid()) {
276 public function getExt()
278 if (!$this->isValid()) {
282 return $this->types[$this->getType()];
286 * @param integer $max max dimension
289 public function scaleDown($max)
291 if (!$this->isValid()) {
295 $width = $this->getWidth();
296 $height = $this->getHeight();
298 if ((! $width)|| (! $height)) {
302 if ($width > $max && $height > $max) {
303 // very tall image (greater than 16:9)
304 // constrain the width - let the height float.
306 if ((($height * 9) / 16) > $width) {
308 $dest_height = intval(($height * $max) / $width);
309 } elseif ($width > $height) {
310 // else constrain both dimensions
312 $dest_height = intval(($height * $max) / $width);
314 $dest_width = intval(($width * $max) / $height);
320 $dest_height = intval(($height * $max) / $width);
322 if ($height > $max) {
323 // very tall image (greater than 16:9)
324 // but width is OK - don't do anything
326 if ((($height * 9) / 16) > $width) {
327 $dest_width = $width;
328 $dest_height = $height;
330 $dest_width = intval(($width * $max) / $height);
334 $dest_width = $width;
335 $dest_height = $height;
340 return $this->scale($dest_width, $dest_height);
344 * @param integer $degrees degrees to rotate image
347 public function rotate($degrees)
349 if (!$this->isValid()) {
353 if ($this->isImagick()) {
354 $this->image->setFirstIterator();
356 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
357 } while ($this->image->nextImage());
361 // if script dies at this point check memory_limit setting in php.ini
362 $this->image = imagerotate($this->image, $degrees, 0);
363 $this->width = imagesx($this->image);
364 $this->height = imagesy($this->image);
368 * @param boolean $horiz optional, default true
369 * @param boolean $vert optional, default false
372 public function flip($horiz = true, $vert = false)
374 if (!$this->isValid()) {
378 if ($this->isImagick()) {
379 $this->image->setFirstIterator();
382 $this->image->flipImage();
385 $this->image->flopImage();
387 } while ($this->image->nextImage());
391 $w = imagesx($this->image);
392 $h = imagesy($this->image);
393 $flipped = imagecreate($w, $h);
395 for ($x = 0; $x < $w; $x++) {
396 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
400 for ($y = 0; $y < $h; $y++) {
401 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
404 $this->image = $flipped;
408 * @param string $filename filename
411 public function orient($filename)
413 if ($this->isImagick()) {
414 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
415 $orientation = $this->image->getImageOrientation();
416 switch ($orientation) {
417 case Imagick::ORIENTATION_BOTTOMRIGHT:
418 $this->image->rotateimage("#000", 180);
420 case Imagick::ORIENTATION_RIGHTTOP:
421 $this->image->rotateimage("#000", 90);
423 case Imagick::ORIENTATION_LEFTBOTTOM:
424 $this->image->rotateimage("#000", -90);
428 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
431 // based off comment on http://php.net/manual/en/function.imagerotate.php
433 if (!$this->isValid()) {
437 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
441 $exif = @exif_read_data($filename, null, true);
446 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
452 case 2: // horizontal flip
456 case 3: // 180 rotate left
460 case 4: // vertical flip
461 $this->flip(false, true);
464 case 5: // vertical flip + 90 rotate right
465 $this->flip(false, true);
469 case 6: // 90 rotate right
473 case 7: // horizontal flip + 90 rotate right
478 case 8: // 90 rotate left
483 // Logger::log('exif: ' . print_r($exif,true));
488 * @param integer $min minimum dimension
491 public function scaleUp($min)
493 if (!$this->isValid()) {
497 $width = $this->getWidth();
498 $height = $this->getHeight();
500 if ((!$width)|| (!$height)) {
504 if ($width < $min && $height < $min) {
505 if ($width > $height) {
507 $dest_height = intval(($height * $min) / $width);
509 $dest_width = intval(($width * $min) / $height);
515 $dest_height = intval(($height * $min) / $width);
517 if ($height < $min) {
518 $dest_width = intval(($width * $min) / $height);
521 $dest_width = $width;
522 $dest_height = $height;
527 return $this->scale($dest_width, $dest_height);
531 * @param integer $dim dimension
534 public function scaleToSquare($dim)
536 if (!$this->isValid()) {
540 return $this->scale($dim, $dim);
544 * @brief Scale image to target dimensions
546 * @param int $dest_width
547 * @param int $dest_height
550 private function scale($dest_width, $dest_height)
552 if (!$this->isValid()) {
556 if ($this->isImagick()) {
558 * If it is not animated, there will be only one iteration here,
559 * so don't bother checking
561 // Don't forget to go back to the first frame
562 $this->image->setFirstIterator();
564 // FIXME - implement horizontal bias for scaling as in following GD functions
565 // to allow very tall images to be constrained only horizontally.
566 $this->image->scaleImage($dest_width, $dest_height);
567 } while ($this->image->nextImage());
569 // These may not be necessary anymore
570 $this->width = $this->image->getImageWidth();
571 $this->height = $this->image->getImageHeight();
573 $dest = imagecreatetruecolor($dest_width, $dest_height);
574 imagealphablending($dest, false);
575 imagesavealpha($dest, true);
577 if ($this->type=='image/png') {
578 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
581 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
584 imagedestroy($this->image);
587 $this->image = $dest;
588 $this->width = imagesx($this->image);
589 $this->height = imagesy($this->image);
596 * @param integer $max maximum
597 * @param integer $x x coordinate
598 * @param integer $y y coordinate
599 * @param integer $w width
600 * @param integer $h height
603 public function crop($max, $x, $y, $w, $h)
605 if (!$this->isValid()) {
609 if ($this->isImagick()) {
610 $this->image->setFirstIterator();
612 $this->image->cropImage($w, $h, $x, $y);
614 * We need to remove the canva,
615 * or the image is not resized to the crop:
616 * http://php.net/manual/en/imagick.cropimage.php#97232
618 $this->image->setImagePage(0, 0, 0, 0);
619 } while ($this->image->nextImage());
620 return $this->scaleDown($max);
623 $dest = imagecreatetruecolor($max, $max);
624 imagealphablending($dest, false);
625 imagesavealpha($dest, true);
626 if ($this->type=='image/png') {
627 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
629 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
631 imagedestroy($this->image);
633 $this->image = $dest;
634 $this->width = imagesx($this->image);
635 $this->height = imagesy($this->image);
639 * @param string $path file path
641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
659 * @brief Magic method allowing string casting of an Image object
661 * Ex: $data = $Image->asString();
663 * $data = (string) $Image;
666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
668 public function __toString() {
669 return $this->asString();
674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
676 public function asString()
678 if (!$this->isValid()) {
682 if ($this->isImagick()) {
684 $this->image = $this->image->deconstructImages();
685 $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
720 * @param string $header passed headers to take into account
723 * @throws \ImagickException
725 public static function guessType($filename, $fromcurl = false, $header = '')
727 Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
731 $h = explode("\n", $header);
733 $data = array_map("trim", explode(":", trim($l), 2));
734 if (count($data) > 1) {
739 if (array_key_exists('Content-Type', $headers))
740 $type = $headers['Content-Type'];
742 if (is_null($type)) {
743 // Guessing from extension? Isn't that... dangerous?
744 if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
746 * Well, this not much better,
747 * but at least it comes from the data inside the image,
748 * we won't be tricked by a manipulated extension
750 $image = new Imagick($filename);
751 $type = $image->getImageMimeType();
752 $image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
754 $ext = pathinfo($filename, PATHINFO_EXTENSION);
755 $types = self::supportedTypes();
756 $type = "image/jpeg";
757 foreach ($types as $m => $e) {
764 Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
769 * @param string $url url
771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
773 public static function getInfoFromURL($url)
781 $data = Cache::get($url);
783 if (is_null($data) || !$data || !is_array($data)) {
784 $img_str = Network::fetchUrl($url, true, $redirects, 4);
790 $filesize = strlen($img_str);
793 if (function_exists("getimagesizefromstring")) {
794 $data = @getimagesizefromstring($img_str);
796 $tempfile = tempnam(get_temppath(), "cache");
799 $stamp1 = microtime(true);
800 file_put_contents($tempfile, $img_str);
801 $a->getProfiler()->saveTimestamp($stamp1, "file", System::callstack());
803 $data = getimagesize($tempfile);
806 } catch (Exception $e) {
811 $data["size"] = $filesize;
814 Cache::set($url, $data);
821 * @param integer $width width
822 * @param integer $height height
823 * @param integer $max max
826 public static function getScalingDimensions($width, $height, $max)
828 if ((!$width) || (!$height)) {
832 if ($width > $max && $height > $max) {
833 // very tall image (greater than 16:9)
834 // constrain the width - let the height float.
836 if ((($height * 9) / 16) > $width) {
838 $dest_height = intval(($height * $max) / $width);
839 } elseif ($width > $height) {
840 // else constrain both dimensions
842 $dest_height = intval(($height * $max) / $width);
844 $dest_width = intval(($width * $max) / $height);
850 $dest_height = intval(($height * $max) / $width);
852 if ($height > $max) {
853 // very tall image (greater than 16:9)
854 // but width is OK - don't do anything
856 if ((($height * 9) / 16) > $width) {
857 $dest_width = $width;
858 $dest_height = $height;
860 $dest_width = intval(($width * $max) / $height);
864 $dest_width = $width;
865 $dest_height = $height;
869 return ["width" => $dest_width, "height" => $dest_height];