3 * @copyright Copyright (C) 2010-2022, 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 use kornrunner\Blurhash\Blurhash;
34 * Class to handle images
38 /** @var GDImage|Imagick|resource */
42 * Put back gd stuff, not everybody have Imagick
54 * @param string $data Image data
55 * @param string $type optional, default null
56 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57 * @throws \ImagickException
59 public function __construct(string $data, string $type = null)
61 $this->imagick = class_exists('Imagick');
62 $this->types = Images::supportedTypes();
63 if (!array_key_exists($type, $this->types)) {
68 if ($this->isImagick() && (empty($data) || $this->loadData($data))) {
71 // Failed to load with Imagick, fallback
72 $this->imagick = false;
74 $this->loadData($data);
82 public function __destruct()
85 if ($this->isImagick()) {
86 $this->image->clear();
87 $this->image->destroy();
90 if (is_resource($this->image)) {
91 imagedestroy($this->image);
99 public function isImagick()
101 return $this->imagick;
105 * Loads image data into handler class
107 * @param string $data Image data
108 * @return boolean Success
109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110 * @throws \ImagickException
112 private function loadData(string $data): bool
114 if ($this->isImagick()) {
115 $this->image = new Imagick();
117 $this->image->readImageBlob($data);
118 } catch (Exception $e) {
119 // Imagick couldn't use the data
124 * Setup the image to the format it will be saved to
126 $map = Images::getFormatsMap();
127 $format = $map[$this->type];
128 $this->image->setFormat($format);
130 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
132 $this->image = $this->image->coalesceImages();
133 } catch (Exception $e) {
138 * setup the compression here, so we'll do it only once
140 switch ($this->getType()) {
142 $quality = DI::config()->get('system', 'png_quality');
144 * From http://www.imagemagick.org/script/command-line-options.php#quality:
146 * 'For the MNG and PNG image formats, the quality value sets
147 * the zlib compression level (quality / 10) and filter-type (quality % 10).
148 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
149 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
151 $quality = $quality * 10;
152 $this->image->setCompressionQuality($quality);
157 $quality = DI::config()->get('system', 'jpeg_quality');
158 $this->image->setCompressionQuality($quality);
161 // The 'width' and 'height' properties are only used by non-Imagick routines.
162 $this->width = $this->image->getImageWidth();
163 $this->height = $this->image->getImageHeight();
169 $this->valid = false;
171 $this->image = @imagecreatefromstring($data);
172 if ($this->image !== false) {
173 $this->width = imagesx($this->image);
174 $this->height = imagesy($this->image);
176 imagealphablending($this->image, false);
177 imagesavealpha($this->image, true);
181 } catch (\Throwable $error) {
182 /** @see https://github.com/php/doc-en/commit/d09a881a8e9059d11e756ee59d75bf404d6941ed */
183 if (strstr($error->getMessage(), "gd-webp cannot allocate temporary buffer")) {
184 DI::logger()->notice('Image is probably animated and therefore unsupported', ['error' => $error]);
186 DI::logger()->warning('Unexpected throwable.', ['error' => $error]);
196 public function isValid(): bool
198 if ($this->isImagick()) {
199 return ($this->image !== false);
207 public function getWidth()
209 if (!$this->isValid()) {
213 if ($this->isImagick()) {
214 return $this->image->getImageWidth();
222 public function getHeight()
224 if (!$this->isValid()) {
228 if ($this->isImagick()) {
229 return $this->image->getImageHeight();
231 return $this->height;
237 public function getImage()
239 if (!$this->isValid()) {
243 if ($this->isImagick()) {
246 $this->image = $this->image->deconstructImages();
248 } catch (Exception $e) {
258 public function getType()
260 if (!$this->isValid()) {
270 public function getExt()
272 if (!$this->isValid()) {
276 return $this->types[$this->getType()];
282 * @param integer $max max dimension
285 public function scaleDown(int $max)
287 if (!$this->isValid()) {
291 $width = $this->getWidth();
292 $height = $this->getHeight();
294 if ((! $width)|| (! $height)) {
298 if ($width > $max && $height > $max) {
299 // very tall image (greater than 16:9)
300 // constrain the width - let the height float.
302 if ((($height * 9) / 16) > $width) {
304 $dest_height = intval(($height * $max) / $width);
305 } elseif ($width > $height) {
306 // else constrain both dimensions
308 $dest_height = intval(($height * $max) / $width);
310 $dest_width = intval(($width * $max) / $height);
316 $dest_height = intval(($height * $max) / $width);
318 if ($height > $max) {
319 // very tall image (greater than 16:9)
320 // but width is OK - don't do anything
322 if ((($height * 9) / 16) > $width) {
323 $dest_width = $width;
324 $dest_height = $height;
326 $dest_width = intval(($width * $max) / $height);
330 $dest_width = $width;
331 $dest_height = $height;
336 return $this->scale($dest_width, $dest_height);
342 * @param integer $degrees degrees to rotate image
345 public function rotate(int $degrees)
347 if (!$this->isValid()) {
351 if ($this->isImagick()) {
352 $this->image->setFirstIterator();
354 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
355 } while ($this->image->nextImage());
359 // if script dies at this point check memory_limit setting in php.ini
360 $this->image = imagerotate($this->image, $degrees, 0);
361 $this->width = imagesx($this->image);
362 $this->height = imagesy($this->image);
368 * @param boolean $horiz optional, default true
369 * @param boolean $vert optional, default false
372 public function flip(bool $horiz = true, bool $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 * Fixes orientation and maybe returns EXIF data (?)
410 * @param string $filename Filename
413 public function orient(string $filename)
415 if ($this->isImagick()) {
416 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
417 $orientation = $this->image->getImageOrientation();
418 switch ($orientation) {
419 case Imagick::ORIENTATION_BOTTOMRIGHT:
420 $this->image->rotateimage("#000", 180);
422 case Imagick::ORIENTATION_RIGHTTOP:
423 $this->image->rotateimage("#000", 90);
425 case Imagick::ORIENTATION_LEFTBOTTOM:
426 $this->image->rotateimage("#000", -90);
430 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
433 // based off comment on http://php.net/manual/en/function.imagerotate.php
435 if (!$this->isValid()) {
439 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
443 $exif = @exif_read_data($filename, null, true);
448 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
454 case 2: // horizontal flip
458 case 3: // 180 rotate left
462 case 4: // vertical flip
463 $this->flip(false, true);
466 case 5: // vertical flip + 90 rotate right
467 $this->flip(false, true);
471 case 6: // 90 rotate right
475 case 7: // horizontal flip + 90 rotate right
480 case 8: // 90 rotate left
489 * Rescales image to minimum size
491 * @param integer $min Minimum dimension
494 public function scaleUp(int $min)
496 if (!$this->isValid()) {
500 $width = $this->getWidth();
501 $height = $this->getHeight();
503 if ((!$width)|| (!$height)) {
507 if ($width < $min && $height < $min) {
508 if ($width > $height) {
510 $dest_height = intval(($height * $min) / $width);
512 $dest_width = intval(($width * $min) / $height);
518 $dest_height = intval(($height * $min) / $width);
520 if ($height < $min) {
521 $dest_width = intval(($width * $min) / $height);
524 $dest_width = $width;
525 $dest_height = $height;
530 return $this->scale($dest_width, $dest_height);
534 * Scales image to square
536 * @param integer $dim Dimension
539 public function scaleToSquare(int $dim)
541 if (!$this->isValid()) {
545 return $this->scale($dim, $dim);
549 * Scale image to target dimensions
551 * @param int $dest_width Destination width
552 * @param int $dest_height Destination height
553 * @return boolean Success
555 private function scale(int $dest_width, int $dest_height): bool
557 if (!$this->isValid()) {
561 if ($this->isImagick()) {
563 * If it is not animated, there will be only one iteration here,
564 * so don't bother checking
566 // Don't forget to go back to the first frame
567 $this->image->setFirstIterator();
569 // FIXME - implement horizontal bias for scaling as in following GD functions
570 // to allow very tall images to be constrained only horizontally.
572 $this->image->scaleImage($dest_width, $dest_height);
573 } catch (Exception $e) {
574 // Imagick couldn't use the data
577 } while ($this->image->nextImage());
579 // These may not be necessary anymore
580 $this->width = $this->image->getImageWidth();
581 $this->height = $this->image->getImageHeight();
583 $dest = imagecreatetruecolor($dest_width, $dest_height);
584 imagealphablending($dest, false);
585 imagesavealpha($dest, true);
587 if ($this->type=='image/png') {
588 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
591 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
594 imagedestroy($this->image);
597 $this->image = $dest;
598 $this->width = imagesx($this->image);
599 $this->height = imagesy($this->image);
606 * Convert a GIF to a PNG to make it static
610 public function toStatic()
612 if ($this->type != 'image/gif') {
616 if ($this->isImagick()) {
617 $this->type == 'image/png';
618 $this->image->setFormat('png');
625 * @param integer $max maximum
626 * @param integer $x x coordinate
627 * @param integer $y y coordinate
628 * @param integer $w width
629 * @param integer $h height
632 public function crop(int $max, int $x, int $y, int $w, int $h)
634 if (!$this->isValid()) {
638 if ($this->isImagick()) {
639 $this->image->setFirstIterator();
641 $this->image->cropImage($w, $h, $x, $y);
643 * We need to remove the canva,
644 * or the image is not resized to the crop:
645 * http://php.net/manual/en/imagick.cropimage.php#97232
647 $this->image->setImagePage(0, 0, 0, 0);
648 } while ($this->image->nextImage());
649 return $this->scaleDown($max);
652 $dest = imagecreatetruecolor($max, $max);
653 imagealphablending($dest, false);
654 imagesavealpha($dest, true);
655 if ($this->type=='image/png') {
656 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
658 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
660 imagedestroy($this->image);
662 $this->image = $dest;
663 $this->width = imagesx($this->image);
664 $this->height = imagesy($this->image);
671 * Magic method allowing string casting of an Image object
673 * Ex: $data = $Image->asString();
675 * $data = (string) $Image;
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
680 public function __toString(): string
682 return (string) $this->asString();
686 * Returns image as string or false on failure
689 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
691 public function asString()
693 if (!$this->isValid()) {
697 if ($this->isImagick()) {
700 $this->image = $this->image->deconstructImages();
701 return $this->image->getImagesBlob();
702 } catch (Exception $e) {
707 $stream = fopen('php://memory','r+');
709 // Enable interlacing
710 imageinterlace($this->image, true);
712 switch ($this->getType()) {
714 $quality = DI::config()->get('system', 'png_quality');
715 imagepng($this->image, $stream, $quality);
720 $quality = DI::config()->get('system', 'jpeg_quality');
721 imagejpeg($this->image, $stream, $quality);
725 return stream_get_contents($stream);
729 * Create a blurhash out of a given image string
731 * @param string $img_str
734 public function getBlurHash(): string
736 $image = New Image($this->asString());
741 $width = $image->getWidth();
742 $height = $image->getHeight();
744 if (max($width, $height) > 90) {
745 $image->scaleDown(90);
746 $width = $image->getWidth();
747 $height = $image->getHeight();
751 for ($y = 0; $y < $height; ++$y) {
753 for ($x = 0; $x < $width; ++$x) {
754 if ($image->isImagick()) {
756 $colors = $image->image->getImagePixelColor($x, $y)->getColor();
757 } catch (\Throwable $th) {
760 $row[] = [$colors['r'], $colors['g'], $colors['b']];
762 $index = imagecolorat($image->image, $x, $y);
763 $colors = @imagecolorsforindex($image->image, $index);
764 $row[] = [$colors['red'], $colors['green'], $colors['blue']];
770 // The components define the amount of details (1 to 9).
774 return Blurhash::encode($pixels, $components_x, $components_y);
778 * Create an image out of a blurhash
780 * @param string $blurhash
781 * @param integer $width
782 * @param integer $height
785 public function getFromBlurHash(string $blurhash, int $width, int $height)
787 $scaled = Images::getScalingDimensions($width, $height, 90);
788 $pixels = Blurhash::decode($blurhash, $scaled['width'], $scaled['height']);
790 if ($this->isImagick()) {
791 $this->image = new Imagick();
792 $draw = new ImagickDraw();
793 $this->image->newImage($scaled['width'], $scaled['height'], '', 'png');
795 $this->image = imagecreatetruecolor($scaled['width'], $scaled['height']);
798 for ($y = 0; $y < $scaled['height']; ++$y) {
799 for ($x = 0; $x < $scaled['width']; ++$x) {
800 [$r, $g, $b] = $pixels[$y][$x];
801 if ($this->isImagick()) {
802 $draw->setFillColor("rgb($r, $g, $b)");
803 $draw->point($x, $y);
805 imagesetpixel($this->image, $x, $y, imagecolorallocate($this->image, $r, $g, $b));
810 if ($this->isImagick()) {
811 $this->image->drawImage($draw);
813 $this->width = imagesx($this->image);
814 $this->height = imagesy($this->image);
819 $this->scaleUp(min($width, $height));