3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Object;
26 use Friendica\Util\Images;
31 * Class to handle images
35 /** @var Imagick|resource */
39 * Put back gd stuff, not everybody have Imagick
51 * @param boolean $type optional, default null
52 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
53 * @throws \ImagickException
55 public function __construct($data, $type = null)
57 $this->imagick = class_exists('Imagick');
58 $this->types = Images::supportedTypes();
59 if (!array_key_exists($type, $this->types)) {
64 if ($this->isImagick() && $this->loadData($data)) {
67 // Failed to load with Imagick, fallback
68 $this->imagick = false;
70 return $this->loadData($data);
78 public function __destruct()
81 if ($this->isImagick()) {
82 $this->image->clear();
83 $this->image->destroy();
86 if (is_resource($this->image)) {
87 imagedestroy($this->image);
95 public function isImagick()
97 return $this->imagick;
101 * @param string $data data
103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
104 * @throws \ImagickException
106 private function loadData($data)
108 if ($this->isImagick()) {
109 $this->image = new Imagick();
111 $this->image->readImageBlob($data);
112 } catch (Exception $e) {
113 // Imagick couldn't use the data
118 * Setup the image to the format it will be saved to
120 $map = Images::getFormatsMap();
121 $format = $map[$this->type];
122 $this->image->setFormat($format);
124 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
126 $this->image = $this->image->coalesceImages();
127 } catch (Exception $e) {
132 * setup the compression here, so we'll do it only once
134 switch ($this->getType()) {
136 $quality = DI::config()->get('system', 'png_quality');
137 if ((! $quality) || ($quality > 9)) {
138 $quality = PNG_QUALITY;
141 * From http://www.imagemagick.org/script/command-line-options.php#quality:
143 * 'For the MNG and PNG image formats, the quality value sets
144 * the zlib compression level (quality / 10) and filter-type (quality % 10).
145 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
146 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
148 $quality = $quality * 10;
149 $this->image->setCompressionQuality($quality);
152 $quality = DI::config()->get('system', 'jpeg_quality');
153 if ((! $quality) || ($quality > 100)) {
154 $quality = JPEG_QUALITY;
156 $this->image->setCompressionQuality($quality);
159 // The 'width' and 'height' properties are only used by non-Imagick routines.
160 $this->width = $this->image->getImageWidth();
161 $this->height = $this->image->getImageHeight();
167 $this->valid = false;
168 $this->image = @imagecreatefromstring($data);
169 if ($this->image !== false) {
170 $this->width = imagesx($this->image);
171 $this->height = imagesy($this->image);
173 imagealphablending($this->image, false);
174 imagesavealpha($this->image, true);
185 public function isValid()
187 if ($this->isImagick()) {
188 return ($this->image !== false);
196 public function getWidth()
198 if (!$this->isValid()) {
202 if ($this->isImagick()) {
203 return $this->image->getImageWidth();
211 public function getHeight()
213 if (!$this->isValid()) {
217 if ($this->isImagick()) {
218 return $this->image->getImageHeight();
220 return $this->height;
226 public function getImage()
228 if (!$this->isValid()) {
232 if ($this->isImagick()) {
235 $this->image = $this->image->deconstructImages();
237 } catch (Exception $e) {
247 public function getType()
249 if (!$this->isValid()) {
259 public function getExt()
261 if (!$this->isValid()) {
265 return $this->types[$this->getType()];
269 * @param integer $max max dimension
272 public function scaleDown($max)
274 if (!$this->isValid()) {
278 $width = $this->getWidth();
279 $height = $this->getHeight();
281 if ((! $width)|| (! $height)) {
285 if ($width > $max && $height > $max) {
286 // very tall image (greater than 16:9)
287 // constrain the width - let the height float.
289 if ((($height * 9) / 16) > $width) {
291 $dest_height = intval(($height * $max) / $width);
292 } elseif ($width > $height) {
293 // else constrain both dimensions
295 $dest_height = intval(($height * $max) / $width);
297 $dest_width = intval(($width * $max) / $height);
303 $dest_height = intval(($height * $max) / $width);
305 if ($height > $max) {
306 // very tall image (greater than 16:9)
307 // but width is OK - don't do anything
309 if ((($height * 9) / 16) > $width) {
310 $dest_width = $width;
311 $dest_height = $height;
313 $dest_width = intval(($width * $max) / $height);
317 $dest_width = $width;
318 $dest_height = $height;
323 return $this->scale($dest_width, $dest_height);
327 * @param integer $degrees degrees to rotate image
330 public function rotate($degrees)
332 if (!$this->isValid()) {
336 if ($this->isImagick()) {
337 $this->image->setFirstIterator();
339 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
340 } while ($this->image->nextImage());
344 // if script dies at this point check memory_limit setting in php.ini
345 $this->image = imagerotate($this->image, $degrees, 0);
346 $this->width = imagesx($this->image);
347 $this->height = imagesy($this->image);
351 * @param boolean $horiz optional, default true
352 * @param boolean $vert optional, default false
355 public function flip($horiz = true, $vert = false)
357 if (!$this->isValid()) {
361 if ($this->isImagick()) {
362 $this->image->setFirstIterator();
365 $this->image->flipImage();
368 $this->image->flopImage();
370 } while ($this->image->nextImage());
374 $w = imagesx($this->image);
375 $h = imagesy($this->image);
376 $flipped = imagecreate($w, $h);
378 for ($x = 0; $x < $w; $x++) {
379 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
383 for ($y = 0; $y < $h; $y++) {
384 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
387 $this->image = $flipped;
391 * @param string $filename filename
394 public function orient($filename)
396 if ($this->isImagick()) {
397 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
398 $orientation = $this->image->getImageOrientation();
399 switch ($orientation) {
400 case Imagick::ORIENTATION_BOTTOMRIGHT:
401 $this->image->rotateimage("#000", 180);
403 case Imagick::ORIENTATION_RIGHTTOP:
404 $this->image->rotateimage("#000", 90);
406 case Imagick::ORIENTATION_LEFTBOTTOM:
407 $this->image->rotateimage("#000", -90);
411 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
414 // based off comment on http://php.net/manual/en/function.imagerotate.php
416 if (!$this->isValid()) {
420 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
424 $exif = @exif_read_data($filename, null, true);
429 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
435 case 2: // horizontal flip
439 case 3: // 180 rotate left
443 case 4: // vertical flip
444 $this->flip(false, true);
447 case 5: // vertical flip + 90 rotate right
448 $this->flip(false, true);
452 case 6: // 90 rotate right
456 case 7: // horizontal flip + 90 rotate right
461 case 8: // 90 rotate left
470 * @param integer $min minimum dimension
473 public function scaleUp($min)
475 if (!$this->isValid()) {
479 $width = $this->getWidth();
480 $height = $this->getHeight();
482 if ((!$width)|| (!$height)) {
486 if ($width < $min && $height < $min) {
487 if ($width > $height) {
489 $dest_height = intval(($height * $min) / $width);
491 $dest_width = intval(($width * $min) / $height);
497 $dest_height = intval(($height * $min) / $width);
499 if ($height < $min) {
500 $dest_width = intval(($width * $min) / $height);
503 $dest_width = $width;
504 $dest_height = $height;
509 return $this->scale($dest_width, $dest_height);
513 * @param integer $dim dimension
516 public function scaleToSquare($dim)
518 if (!$this->isValid()) {
522 return $this->scale($dim, $dim);
526 * Scale image to target dimensions
528 * @param int $dest_width
529 * @param int $dest_height
532 private function scale($dest_width, $dest_height)
534 if (!$this->isValid()) {
538 if ($this->isImagick()) {
540 * If it is not animated, there will be only one iteration here,
541 * so don't bother checking
543 // Don't forget to go back to the first frame
544 $this->image->setFirstIterator();
546 // FIXME - implement horizontal bias for scaling as in following GD functions
547 // to allow very tall images to be constrained only horizontally.
549 $this->image->scaleImage($dest_width, $dest_height);
550 } catch (Exception $e) {
551 // Imagick couldn't use the data
554 } while ($this->image->nextImage());
556 // These may not be necessary anymore
557 $this->width = $this->image->getImageWidth();
558 $this->height = $this->image->getImageHeight();
560 $dest = imagecreatetruecolor($dest_width, $dest_height);
561 imagealphablending($dest, false);
562 imagesavealpha($dest, true);
564 if ($this->type=='image/png') {
565 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
568 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
571 imagedestroy($this->image);
574 $this->image = $dest;
575 $this->width = imagesx($this->image);
576 $this->height = imagesy($this->image);
583 * Convert a GIF to a PNG to make it static
585 public function toStatic()
587 if ($this->type != 'image/gif') {
591 if ($this->isImagick()) {
592 $this->type == 'image/png';
593 $this->image->setFormat('png');
598 * @param integer $max maximum
599 * @param integer $x x coordinate
600 * @param integer $y y coordinate
601 * @param integer $w width
602 * @param integer $h height
605 public function crop($max, $x, $y, $w, $h)
607 if (!$this->isValid()) {
611 if ($this->isImagick()) {
612 $this->image->setFirstIterator();
614 $this->image->cropImage($w, $h, $x, $y);
616 * We need to remove the canva,
617 * or the image is not resized to the crop:
618 * http://php.net/manual/en/imagick.cropimage.php#97232
620 $this->image->setImagePage(0, 0, 0, 0);
621 } while ($this->image->nextImage());
622 return $this->scaleDown($max);
625 $dest = imagecreatetruecolor($max, $max);
626 imagealphablending($dest, false);
627 imagesavealpha($dest, true);
628 if ($this->type=='image/png') {
629 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
631 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
633 imagedestroy($this->image);
635 $this->image = $dest;
636 $this->width = imagesx($this->image);
637 $this->height = imagesy($this->image);
641 * @param string $path file path
643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
645 public function saveToFilePath($path)
647 if (!$this->isValid()) {
651 $string = $this->asString();
653 $stamp1 = microtime(true);
654 file_put_contents($path, $string);
655 DI::profiler()->saveTimestamp($stamp1, "file");
659 * 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()) {
685 $this->image = $this->image->deconstructImages();
686 $string = $this->image->getImagesBlob();
688 } catch (Exception $e) {
695 // Enable interlacing
696 imageinterlace($this->image, true);
698 switch ($this->getType()) {
700 $quality = DI::config()->get('system', 'png_quality');
701 if ((!$quality) || ($quality > 9)) {
702 $quality = PNG_QUALITY;
704 imagepng($this->image, null, $quality);
707 $quality = DI::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 * supported mimetypes and corresponding file extensions
723 * @deprecated in version 2019.12 please use Util\Images::supportedTypes() instead.
725 public static function supportedTypes()
727 return Images::supportedTypes();
731 * Maps Mime types to Imagick formats
733 * @return array With with image formats (mime type as key)
734 * @deprecated in version 2019.12 please use Util\Images::getFormatsMap() instead.
736 public static function getFormatsMap()
738 return Images::getFormatsMap();
742 * @param string $url url
744 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
745 * @deprecated in version 2019.12 please use Util\Images::getInfoFromURLCached() instead.
747 public static function getInfoFromURL($url)
749 return Images::getInfoFromURLCached($url);
753 * @param integer $width width
754 * @param integer $height height
755 * @param integer $max max
757 * @deprecated in version 2019.12 please use Util\Images::getScalingDimensions() instead.
759 public static function getScalingDimensions($width, $height, $max)
761 return Images::getScalingDimensions($width, $height, $max);