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
463 * @param integer $min minimum dimension
466 public function scaleUp($min)
468 if (!$this->isValid()) {
472 $width = $this->getWidth();
473 $height = $this->getHeight();
475 if ((!$width)|| (!$height)) {
479 if ($width < $min && $height < $min) {
480 if ($width > $height) {
482 $dest_height = intval(($height * $min) / $width);
484 $dest_width = intval(($width * $min) / $height);
490 $dest_height = intval(($height * $min) / $width);
492 if ($height < $min) {
493 $dest_width = intval(($width * $min) / $height);
496 $dest_width = $width;
497 $dest_height = $height;
502 return $this->scale($dest_width, $dest_height);
506 * @param integer $dim dimension
509 public function scaleToSquare($dim)
511 if (!$this->isValid()) {
515 return $this->scale($dim, $dim);
519 * Scale image to target dimensions
521 * @param int $dest_width
522 * @param int $dest_height
525 private function scale($dest_width, $dest_height)
527 if (!$this->isValid()) {
531 if ($this->isImagick()) {
533 * If it is not animated, there will be only one iteration here,
534 * so don't bother checking
536 // Don't forget to go back to the first frame
537 $this->image->setFirstIterator();
539 // FIXME - implement horizontal bias for scaling as in following GD functions
540 // to allow very tall images to be constrained only horizontally.
541 $this->image->scaleImage($dest_width, $dest_height);
542 } while ($this->image->nextImage());
544 // These may not be necessary anymore
545 $this->width = $this->image->getImageWidth();
546 $this->height = $this->image->getImageHeight();
548 $dest = imagecreatetruecolor($dest_width, $dest_height);
549 imagealphablending($dest, false);
550 imagesavealpha($dest, true);
552 if ($this->type=='image/png') {
553 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
556 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
559 imagedestroy($this->image);
562 $this->image = $dest;
563 $this->width = imagesx($this->image);
564 $this->height = imagesy($this->image);
571 * @param integer $max maximum
572 * @param integer $x x coordinate
573 * @param integer $y y coordinate
574 * @param integer $w width
575 * @param integer $h height
578 public function crop($max, $x, $y, $w, $h)
580 if (!$this->isValid()) {
584 if ($this->isImagick()) {
585 $this->image->setFirstIterator();
587 $this->image->cropImage($w, $h, $x, $y);
589 * We need to remove the canva,
590 * or the image is not resized to the crop:
591 * http://php.net/manual/en/imagick.cropimage.php#97232
593 $this->image->setImagePage(0, 0, 0, 0);
594 } while ($this->image->nextImage());
595 return $this->scaleDown($max);
598 $dest = imagecreatetruecolor($max, $max);
599 imagealphablending($dest, false);
600 imagesavealpha($dest, true);
601 if ($this->type=='image/png') {
602 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
604 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
606 imagedestroy($this->image);
608 $this->image = $dest;
609 $this->width = imagesx($this->image);
610 $this->height = imagesy($this->image);
614 * @param string $path file path
616 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
618 public function saveToFilePath($path)
620 if (!$this->isValid()) {
624 $string = $this->asString();
626 $stamp1 = microtime(true);
627 file_put_contents($path, $string);
628 DI::profiler()->saveTimestamp($stamp1, "file");
632 * Magic method allowing string casting of an Image object
634 * Ex: $data = $Image->asString();
636 * $data = (string) $Image;
639 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
641 public function __toString() {
642 return $this->asString();
647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
649 public function asString()
651 if (!$this->isValid()) {
655 if ($this->isImagick()) {
657 $this->image = $this->image->deconstructImages();
658 $string = $this->image->getImagesBlob();
664 // Enable interlacing
665 imageinterlace($this->image, true);
667 switch ($this->getType()) {
669 $quality = DI::config()->get('system', 'png_quality');
670 if ((!$quality) || ($quality > 9)) {
671 $quality = PNG_QUALITY;
673 imagepng($this->image, null, $quality);
676 $quality = DI::config()->get('system', 'jpeg_quality');
677 if ((!$quality) || ($quality > 100)) {
678 $quality = JPEG_QUALITY;
680 imagejpeg($this->image, null, $quality);
682 $string = ob_get_contents();
689 * supported mimetypes and corresponding file extensions
692 * @deprecated in version 2019.12 please use Util\Images::supportedTypes() instead.
694 public static function supportedTypes()
696 return Images::supportedTypes();
700 * Maps Mime types to Imagick formats
702 * @return array With with image formats (mime type as key)
703 * @deprecated in version 2019.12 please use Util\Images::getFormatsMap() instead.
705 public static function getFormatsMap()
707 return Images::getFormatsMap();
711 * @param string $url url
713 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
714 * @deprecated in version 2019.12 please use Util\Images::getInfoFromURLCached() instead.
716 public static function getInfoFromURL($url)
718 return Images::getInfoFromURLCached($url);
722 * @param integer $width width
723 * @param integer $height height
724 * @param integer $max max
726 * @deprecated in version 2019.12 please use Util\Images::getScalingDimensions() instead.
728 public static function getScalingDimensions($width, $height, $max)
730 return Images::getScalingDimensions($width, $height, $max);