3 * @copyright Copyright (C) 2020, Friendica
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;
25 use Friendica\Core\System;
27 use Friendica\Util\Images;
32 * Class to handle images
36 /** @var Imagick|resource */
40 * Put back gd stuff, not everybody have Imagick
52 * @param boolean $type optional, default null
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54 * @throws \ImagickException
56 public function __construct($data, $type = null)
58 $this->imagick = class_exists('Imagick');
59 $this->types = Images::supportedTypes();
60 if (!array_key_exists($type, $this->types)) {
65 if ($this->isImagick() && $this->loadData($data)) {
68 // Failed to load with Imagick, fallback
69 $this->imagick = false;
71 return $this->loadData($data);
79 public function __destruct()
82 if ($this->isImagick()) {
83 $this->image->clear();
84 $this->image->destroy();
87 if (is_resource($this->image)) {
88 imagedestroy($this->image);
96 public function isImagick()
98 return $this->imagick;
102 * @param string $data data
104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
105 * @throws \ImagickException
107 private function loadData($data)
109 if ($this->isImagick()) {
110 $this->image = new Imagick();
112 $this->image->readImageBlob($data);
113 } catch (Exception $e) {
114 // Imagick couldn't use the data
119 * Setup the image to the format it will be saved to
121 $map = Images::getFormatsMap();
122 $format = $map[$this->type];
123 $this->image->setFormat($format);
125 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
126 $this->image = $this->image->coalesceImages();
129 * setup the compression here, so we'll do it only once
131 switch ($this->getType()) {
133 $quality = DI::config()->get('system', 'png_quality');
134 if ((! $quality) || ($quality > 9)) {
135 $quality = PNG_QUALITY;
138 * From http://www.imagemagick.org/script/command-line-options.php#quality:
140 * 'For the MNG and PNG image formats, the quality value sets
141 * the zlib compression level (quality / 10) and filter-type (quality % 10).
142 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
143 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
145 $quality = $quality * 10;
146 $this->image->setCompressionQuality($quality);
149 $quality = DI::config()->get('system', 'jpeg_quality');
150 if ((! $quality) || ($quality > 100)) {
151 $quality = JPEG_QUALITY;
153 $this->image->setCompressionQuality($quality);
156 // The 'width' and 'height' properties are only used by non-Imagick routines.
157 $this->width = $this->image->getImageWidth();
158 $this->height = $this->image->getImageHeight();
164 $this->valid = false;
165 $this->image = @imagecreatefromstring($data);
166 if ($this->image !== false) {
167 $this->width = imagesx($this->image);
168 $this->height = imagesy($this->image);
170 imagealphablending($this->image, false);
171 imagesavealpha($this->image, true);
182 public function isValid()
184 if ($this->isImagick()) {
185 return ($this->image !== false);
193 public function getWidth()
195 if (!$this->isValid()) {
199 if ($this->isImagick()) {
200 return $this->image->getImageWidth();
208 public function getHeight()
210 if (!$this->isValid()) {
214 if ($this->isImagick()) {
215 return $this->image->getImageHeight();
217 return $this->height;
223 public function getImage()
225 if (!$this->isValid()) {
229 if ($this->isImagick()) {
231 $this->image = $this->image->deconstructImages();
240 public function getType()
242 if (!$this->isValid()) {
252 public function getExt()
254 if (!$this->isValid()) {
258 return $this->types[$this->getType()];
262 * @param integer $max max dimension
265 public function scaleDown($max)
267 if (!$this->isValid()) {
271 $width = $this->getWidth();
272 $height = $this->getHeight();
274 if ((! $width)|| (! $height)) {
278 if ($width > $max && $height > $max) {
279 // very tall image (greater than 16:9)
280 // constrain the width - let the height float.
282 if ((($height * 9) / 16) > $width) {
284 $dest_height = intval(($height * $max) / $width);
285 } elseif ($width > $height) {
286 // else constrain both dimensions
288 $dest_height = intval(($height * $max) / $width);
290 $dest_width = intval(($width * $max) / $height);
296 $dest_height = intval(($height * $max) / $width);
298 if ($height > $max) {
299 // very tall image (greater than 16:9)
300 // but width is OK - don't do anything
302 if ((($height * 9) / 16) > $width) {
303 $dest_width = $width;
304 $dest_height = $height;
306 $dest_width = intval(($width * $max) / $height);
310 $dest_width = $width;
311 $dest_height = $height;
316 return $this->scale($dest_width, $dest_height);
320 * @param integer $degrees degrees to rotate image
323 public function rotate($degrees)
325 if (!$this->isValid()) {
329 if ($this->isImagick()) {
330 $this->image->setFirstIterator();
332 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
333 } while ($this->image->nextImage());
337 // if script dies at this point check memory_limit setting in php.ini
338 $this->image = imagerotate($this->image, $degrees, 0);
339 $this->width = imagesx($this->image);
340 $this->height = imagesy($this->image);
344 * @param boolean $horiz optional, default true
345 * @param boolean $vert optional, default false
348 public function flip($horiz = true, $vert = false)
350 if (!$this->isValid()) {
354 if ($this->isImagick()) {
355 $this->image->setFirstIterator();
358 $this->image->flipImage();
361 $this->image->flopImage();
363 } while ($this->image->nextImage());
367 $w = imagesx($this->image);
368 $h = imagesy($this->image);
369 $flipped = imagecreate($w, $h);
371 for ($x = 0; $x < $w; $x++) {
372 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
376 for ($y = 0; $y < $h; $y++) {
377 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
380 $this->image = $flipped;
384 * @param string $filename filename
387 public function orient($filename)
389 if ($this->isImagick()) {
390 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
391 $orientation = $this->image->getImageOrientation();
392 switch ($orientation) {
393 case Imagick::ORIENTATION_BOTTOMRIGHT:
394 $this->image->rotateimage("#000", 180);
396 case Imagick::ORIENTATION_RIGHTTOP:
397 $this->image->rotateimage("#000", 90);
399 case Imagick::ORIENTATION_LEFTBOTTOM:
400 $this->image->rotateimage("#000", -90);
404 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
407 // based off comment on http://php.net/manual/en/function.imagerotate.php
409 if (!$this->isValid()) {
413 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
417 $exif = @exif_read_data($filename, null, true);
422 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
428 case 2: // horizontal flip
432 case 3: // 180 rotate left
436 case 4: // vertical flip
437 $this->flip(false, true);
440 case 5: // vertical flip + 90 rotate right
441 $this->flip(false, true);
445 case 6: // 90 rotate right
449 case 7: // horizontal flip + 90 rotate right
454 case 8: // 90 rotate left
459 // Logger::log('exif: ' . print_r($exif,true));
464 * @param integer $min minimum dimension
467 public function scaleUp($min)
469 if (!$this->isValid()) {
473 $width = $this->getWidth();
474 $height = $this->getHeight();
476 if ((!$width)|| (!$height)) {
480 if ($width < $min && $height < $min) {
481 if ($width > $height) {
483 $dest_height = intval(($height * $min) / $width);
485 $dest_width = intval(($width * $min) / $height);
491 $dest_height = intval(($height * $min) / $width);
493 if ($height < $min) {
494 $dest_width = intval(($width * $min) / $height);
497 $dest_width = $width;
498 $dest_height = $height;
503 return $this->scale($dest_width, $dest_height);
507 * @param integer $dim dimension
510 public function scaleToSquare($dim)
512 if (!$this->isValid()) {
516 return $this->scale($dim, $dim);
520 * Scale image to target dimensions
522 * @param int $dest_width
523 * @param int $dest_height
526 private function scale($dest_width, $dest_height)
528 if (!$this->isValid()) {
532 if ($this->isImagick()) {
534 * If it is not animated, there will be only one iteration here,
535 * so don't bother checking
537 // Don't forget to go back to the first frame
538 $this->image->setFirstIterator();
540 // FIXME - implement horizontal bias for scaling as in following GD functions
541 // to allow very tall images to be constrained only horizontally.
542 $this->image->scaleImage($dest_width, $dest_height);
543 } while ($this->image->nextImage());
545 // These may not be necessary anymore
546 $this->width = $this->image->getImageWidth();
547 $this->height = $this->image->getImageHeight();
549 $dest = imagecreatetruecolor($dest_width, $dest_height);
550 imagealphablending($dest, false);
551 imagesavealpha($dest, true);
553 if ($this->type=='image/png') {
554 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
557 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
560 imagedestroy($this->image);
563 $this->image = $dest;
564 $this->width = imagesx($this->image);
565 $this->height = imagesy($this->image);
572 * @param integer $max maximum
573 * @param integer $x x coordinate
574 * @param integer $y y coordinate
575 * @param integer $w width
576 * @param integer $h height
579 public function crop($max, $x, $y, $w, $h)
581 if (!$this->isValid()) {
585 if ($this->isImagick()) {
586 $this->image->setFirstIterator();
588 $this->image->cropImage($w, $h, $x, $y);
590 * We need to remove the canva,
591 * or the image is not resized to the crop:
592 * http://php.net/manual/en/imagick.cropimage.php#97232
594 $this->image->setImagePage(0, 0, 0, 0);
595 } while ($this->image->nextImage());
596 return $this->scaleDown($max);
599 $dest = imagecreatetruecolor($max, $max);
600 imagealphablending($dest, false);
601 imagesavealpha($dest, true);
602 if ($this->type=='image/png') {
603 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
605 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
607 imagedestroy($this->image);
609 $this->image = $dest;
610 $this->width = imagesx($this->image);
611 $this->height = imagesy($this->image);
615 * @param string $path file path
617 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
619 public function saveToFilePath($path)
621 if (!$this->isValid()) {
625 $string = $this->asString();
627 $stamp1 = microtime(true);
628 file_put_contents($path, $string);
629 DI::profiler()->saveTimestamp($stamp1, "file", System::callstack());
633 * Magic method allowing string casting of an Image object
635 * Ex: $data = $Image->asString();
637 * $data = (string) $Image;
640 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
642 public function __toString() {
643 return $this->asString();
648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
650 public function asString()
652 if (!$this->isValid()) {
656 if ($this->isImagick()) {
658 $this->image = $this->image->deconstructImages();
659 $string = $this->image->getImagesBlob();
665 // Enable interlacing
666 imageinterlace($this->image, true);
668 switch ($this->getType()) {
670 $quality = DI::config()->get('system', 'png_quality');
671 if ((!$quality) || ($quality > 9)) {
672 $quality = PNG_QUALITY;
674 imagepng($this->image, null, $quality);
677 $quality = DI::config()->get('system', 'jpeg_quality');
678 if ((!$quality) || ($quality > 100)) {
679 $quality = JPEG_QUALITY;
681 imagejpeg($this->image, null, $quality);
683 $string = ob_get_contents();
690 * supported mimetypes and corresponding file extensions
693 * @deprecated in version 2019.12 please use Util\Images::supportedTypes() instead.
695 public static function supportedTypes()
697 return Images::supportedTypes();
701 * Maps Mime types to Imagick formats
703 * @return array With with image formats (mime type as key)
704 * @deprecated in version 2019.12 please use Util\Images::getFormatsMap() instead.
706 public static function getFormatsMap()
708 return Images::getFormatsMap();
712 * @param string $url url
714 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
715 * @deprecated in version 2019.12 please use Util\Images::getInfoFromURLCached() instead.
717 public static function getInfoFromURL($url)
719 return Images::getInfoFromURLCached($url);
723 * @param integer $width width
724 * @param integer $height height
725 * @param integer $max max
727 * @deprecated in version 2019.12 please use Util\Images::getScalingDimensions() instead.
729 public static function getScalingDimensions($width, $height, $max)
731 return Images::getScalingDimensions($width, $height, $max);