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;
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()) {
234 $this->image = $this->image->deconstructImages();
243 public function getType()
245 if (!$this->isValid()) {
255 public function getExt()
257 if (!$this->isValid()) {
261 return $this->types[$this->getType()];
265 * @param integer $max max dimension
268 public function scaleDown($max)
270 if (!$this->isValid()) {
274 $width = $this->getWidth();
275 $height = $this->getHeight();
277 if ((! $width)|| (! $height)) {
281 if ($width > $max && $height > $max) {
282 // very tall image (greater than 16:9)
283 // constrain the width - let the height float.
285 if ((($height * 9) / 16) > $width) {
287 $dest_height = intval(($height * $max) / $width);
288 } elseif ($width > $height) {
289 // else constrain both dimensions
291 $dest_height = intval(($height * $max) / $width);
293 $dest_width = intval(($width * $max) / $height);
299 $dest_height = intval(($height * $max) / $width);
301 if ($height > $max) {
302 // very tall image (greater than 16:9)
303 // but width is OK - don't do anything
305 if ((($height * 9) / 16) > $width) {
306 $dest_width = $width;
307 $dest_height = $height;
309 $dest_width = intval(($width * $max) / $height);
313 $dest_width = $width;
314 $dest_height = $height;
319 return $this->scale($dest_width, $dest_height);
323 * @param integer $degrees degrees to rotate image
326 public function rotate($degrees)
328 if (!$this->isValid()) {
332 if ($this->isImagick()) {
333 $this->image->setFirstIterator();
335 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
336 } while ($this->image->nextImage());
340 // if script dies at this point check memory_limit setting in php.ini
341 $this->image = imagerotate($this->image, $degrees, 0);
342 $this->width = imagesx($this->image);
343 $this->height = imagesy($this->image);
347 * @param boolean $horiz optional, default true
348 * @param boolean $vert optional, default false
351 public function flip($horiz = true, $vert = false)
353 if (!$this->isValid()) {
357 if ($this->isImagick()) {
358 $this->image->setFirstIterator();
361 $this->image->flipImage();
364 $this->image->flopImage();
366 } while ($this->image->nextImage());
370 $w = imagesx($this->image);
371 $h = imagesy($this->image);
372 $flipped = imagecreate($w, $h);
374 for ($x = 0; $x < $w; $x++) {
375 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
379 for ($y = 0; $y < $h; $y++) {
380 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
383 $this->image = $flipped;
387 * @param string $filename filename
390 public function orient($filename)
392 if ($this->isImagick()) {
393 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
394 $orientation = $this->image->getImageOrientation();
395 switch ($orientation) {
396 case Imagick::ORIENTATION_BOTTOMRIGHT:
397 $this->image->rotateimage("#000", 180);
399 case Imagick::ORIENTATION_RIGHTTOP:
400 $this->image->rotateimage("#000", 90);
402 case Imagick::ORIENTATION_LEFTBOTTOM:
403 $this->image->rotateimage("#000", -90);
407 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
410 // based off comment on http://php.net/manual/en/function.imagerotate.php
412 if (!$this->isValid()) {
416 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
420 $exif = @exif_read_data($filename, null, true);
425 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
431 case 2: // horizontal flip
435 case 3: // 180 rotate left
439 case 4: // vertical flip
440 $this->flip(false, true);
443 case 5: // vertical flip + 90 rotate right
444 $this->flip(false, true);
448 case 6: // 90 rotate right
452 case 7: // horizontal flip + 90 rotate right
457 case 8: // 90 rotate left
466 * @param integer $min minimum dimension
469 public function scaleUp($min)
471 if (!$this->isValid()) {
475 $width = $this->getWidth();
476 $height = $this->getHeight();
478 if ((!$width)|| (!$height)) {
482 if ($width < $min && $height < $min) {
483 if ($width > $height) {
485 $dest_height = intval(($height * $min) / $width);
487 $dest_width = intval(($width * $min) / $height);
493 $dest_height = intval(($height * $min) / $width);
495 if ($height < $min) {
496 $dest_width = intval(($width * $min) / $height);
499 $dest_width = $width;
500 $dest_height = $height;
505 return $this->scale($dest_width, $dest_height);
509 * @param integer $dim dimension
512 public function scaleToSquare($dim)
514 if (!$this->isValid()) {
518 return $this->scale($dim, $dim);
522 * Scale image to target dimensions
524 * @param int $dest_width
525 * @param int $dest_height
528 private function scale($dest_width, $dest_height)
530 if (!$this->isValid()) {
534 if ($this->isImagick()) {
536 * If it is not animated, there will be only one iteration here,
537 * so don't bother checking
539 // Don't forget to go back to the first frame
540 $this->image->setFirstIterator();
542 // FIXME - implement horizontal bias for scaling as in following GD functions
543 // to allow very tall images to be constrained only horizontally.
545 $this->image->scaleImage($dest_width, $dest_height);
546 } catch (Exception $e) {
547 // Imagick couldn't use the data
550 } while ($this->image->nextImage());
552 // These may not be necessary anymore
553 $this->width = $this->image->getImageWidth();
554 $this->height = $this->image->getImageHeight();
556 $dest = imagecreatetruecolor($dest_width, $dest_height);
557 imagealphablending($dest, false);
558 imagesavealpha($dest, true);
560 if ($this->type=='image/png') {
561 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
564 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
567 imagedestroy($this->image);
570 $this->image = $dest;
571 $this->width = imagesx($this->image);
572 $this->height = imagesy($this->image);
579 * Convert a GIF to a PNG to make it static
581 public function toStatic()
583 if ($this->type != 'image/gif') {
587 if ($this->isImagick()) {
588 $this->type == 'image/png';
589 $this->image->setFormat('png');
594 * @param integer $max maximum
595 * @param integer $x x coordinate
596 * @param integer $y y coordinate
597 * @param integer $w width
598 * @param integer $h height
601 public function crop($max, $x, $y, $w, $h)
603 if (!$this->isValid()) {
607 if ($this->isImagick()) {
608 $this->image->setFirstIterator();
610 $this->image->cropImage($w, $h, $x, $y);
612 * We need to remove the canva,
613 * or the image is not resized to the crop:
614 * http://php.net/manual/en/imagick.cropimage.php#97232
616 $this->image->setImagePage(0, 0, 0, 0);
617 } while ($this->image->nextImage());
618 return $this->scaleDown($max);
621 $dest = imagecreatetruecolor($max, $max);
622 imagealphablending($dest, false);
623 imagesavealpha($dest, true);
624 if ($this->type=='image/png') {
625 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
627 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
629 imagedestroy($this->image);
631 $this->image = $dest;
632 $this->width = imagesx($this->image);
633 $this->height = imagesy($this->image);
637 * @param string $path file path
639 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
641 public function saveToFilePath($path)
643 if (!$this->isValid()) {
647 $string = $this->asString();
649 $stamp1 = microtime(true);
650 file_put_contents($path, $string);
651 DI::profiler()->saveTimestamp($stamp1, "file");
655 * Magic method allowing string casting of an Image object
657 * Ex: $data = $Image->asString();
659 * $data = (string) $Image;
662 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
664 public function __toString() {
665 return $this->asString();
670 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
672 public function asString()
674 if (!$this->isValid()) {
678 if ($this->isImagick()) {
680 $this->image = $this->image->deconstructImages();
681 $string = $this->image->getImagesBlob();
687 // Enable interlacing
688 imageinterlace($this->image, true);
690 switch ($this->getType()) {
692 $quality = DI::config()->get('system', 'png_quality');
693 if ((!$quality) || ($quality > 9)) {
694 $quality = PNG_QUALITY;
696 imagepng($this->image, null, $quality);
699 $quality = DI::config()->get('system', 'jpeg_quality');
700 if ((!$quality) || ($quality > 100)) {
701 $quality = JPEG_QUALITY;
703 imagejpeg($this->image, null, $quality);
705 $string = ob_get_contents();
712 * supported mimetypes and corresponding file extensions
715 * @deprecated in version 2019.12 please use Util\Images::supportedTypes() instead.
717 public static function supportedTypes()
719 return Images::supportedTypes();
723 * Maps Mime types to Imagick formats
725 * @return array With with image formats (mime type as key)
726 * @deprecated in version 2019.12 please use Util\Images::getFormatsMap() instead.
728 public static function getFormatsMap()
730 return Images::getFormatsMap();
734 * @param string $url url
736 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
737 * @deprecated in version 2019.12 please use Util\Images::getInfoFromURLCached() instead.
739 public static function getInfoFromURL($url)
741 return Images::getInfoFromURLCached($url);
745 * @param integer $width width
746 * @param integer $height height
747 * @param integer $max max
749 * @deprecated in version 2019.12 please use Util\Images::getScalingDimensions() instead.
751 public static function getScalingDimensions($width, $height, $max)
753 return Images::getScalingDimensions($width, $height, $max);