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;
30 use kornrunner\Blurhash\Blurhash;
33 * Class to handle images
37 /** @var GDImage|Imagick|resource */
41 * Put back gd stuff, not everybody have Imagick
53 * @param string $data Image data
54 * @param string $type optional, default null
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56 * @throws \ImagickException
58 public function __construct(string $data, string $type = null)
60 $this->imagick = class_exists('Imagick');
61 $this->types = Images::supportedTypes();
62 if (!array_key_exists($type, $this->types)) {
67 if ($this->isImagick() && $this->loadData($data)) {
70 // Failed to load with Imagick, fallback
71 $this->imagick = false;
73 $this->loadData($data);
81 public function __destruct()
84 if ($this->isImagick()) {
85 $this->image->clear();
86 $this->image->destroy();
89 if (is_resource($this->image)) {
90 imagedestroy($this->image);
98 public function isImagick()
100 return $this->imagick;
104 * Loads image data into handler class
106 * @param string $data Image data
107 * @return boolean Success
108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
109 * @throws \ImagickException
111 private function loadData(string $data): bool
113 if ($this->isImagick()) {
114 $this->image = new Imagick();
116 $this->image->readImageBlob($data);
117 } catch (Exception $e) {
118 // Imagick couldn't use the data
123 * Setup the image to the format it will be saved to
125 $map = Images::getFormatsMap();
126 $format = $map[$this->type];
127 $this->image->setFormat($format);
129 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
131 $this->image = $this->image->coalesceImages();
132 } catch (Exception $e) {
137 * setup the compression here, so we'll do it only once
139 switch ($this->getType()) {
141 $quality = DI::config()->get('system', 'png_quality');
143 * From http://www.imagemagick.org/script/command-line-options.php#quality:
145 * 'For the MNG and PNG image formats, the quality value sets
146 * the zlib compression level (quality / 10) and filter-type (quality % 10).
147 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
148 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
150 $quality = $quality * 10;
151 $this->image->setCompressionQuality($quality);
156 $quality = DI::config()->get('system', 'jpeg_quality');
157 $this->image->setCompressionQuality($quality);
160 // The 'width' and 'height' properties are only used by non-Imagick routines.
161 $this->width = $this->image->getImageWidth();
162 $this->height = $this->image->getImageHeight();
168 $this->valid = false;
170 $this->image = @imagecreatefromstring($data);
171 if ($this->image !== false) {
172 $this->width = imagesx($this->image);
173 $this->height = imagesy($this->image);
175 imagealphablending($this->image, false);
176 imagesavealpha($this->image, true);
180 } catch (\Throwable $error) {
181 /** @see https://github.com/php/doc-en/commit/d09a881a8e9059d11e756ee59d75bf404d6941ed */
182 if (strstr($error->getMessage(), "gd-webp cannot allocate temporary buffer")) {
183 DI::logger()->notice('Image is probably animated and therefore unsupported', ['error' => $error]);
185 DI::logger()->warning('Unexpected throwable.', ['error' => $error]);
195 public function isValid(): bool
197 if ($this->isImagick()) {
198 return ($this->image !== false);
206 public function getWidth()
208 if (!$this->isValid()) {
212 if ($this->isImagick()) {
213 return $this->image->getImageWidth();
221 public function getHeight()
223 if (!$this->isValid()) {
227 if ($this->isImagick()) {
228 return $this->image->getImageHeight();
230 return $this->height;
236 public function getImage()
238 if (!$this->isValid()) {
242 if ($this->isImagick()) {
245 $this->image = $this->image->deconstructImages();
247 } catch (Exception $e) {
257 public function getType()
259 if (!$this->isValid()) {
269 public function getExt()
271 if (!$this->isValid()) {
275 return $this->types[$this->getType()];
281 * @param integer $max max dimension
284 public function scaleDown(int $max)
286 if (!$this->isValid()) {
290 $width = $this->getWidth();
291 $height = $this->getHeight();
293 if ((! $width)|| (! $height)) {
297 if ($width > $max && $height > $max) {
298 // very tall image (greater than 16:9)
299 // constrain the width - let the height float.
301 if ((($height * 9) / 16) > $width) {
303 $dest_height = intval(($height * $max) / $width);
304 } elseif ($width > $height) {
305 // else constrain both dimensions
307 $dest_height = intval(($height * $max) / $width);
309 $dest_width = intval(($width * $max) / $height);
315 $dest_height = intval(($height * $max) / $width);
317 if ($height > $max) {
318 // very tall image (greater than 16:9)
319 // but width is OK - don't do anything
321 if ((($height * 9) / 16) > $width) {
322 $dest_width = $width;
323 $dest_height = $height;
325 $dest_width = intval(($width * $max) / $height);
329 $dest_width = $width;
330 $dest_height = $height;
335 return $this->scale($dest_width, $dest_height);
341 * @param integer $degrees degrees to rotate image
344 public function rotate(int $degrees)
346 if (!$this->isValid()) {
350 if ($this->isImagick()) {
351 $this->image->setFirstIterator();
353 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
354 } while ($this->image->nextImage());
358 // if script dies at this point check memory_limit setting in php.ini
359 $this->image = imagerotate($this->image, $degrees, 0);
360 $this->width = imagesx($this->image);
361 $this->height = imagesy($this->image);
367 * @param boolean $horiz optional, default true
368 * @param boolean $vert optional, default false
371 public function flip(bool $horiz = true, bool $vert = false)
373 if (!$this->isValid()) {
377 if ($this->isImagick()) {
378 $this->image->setFirstIterator();
381 $this->image->flipImage();
384 $this->image->flopImage();
386 } while ($this->image->nextImage());
390 $w = imagesx($this->image);
391 $h = imagesy($this->image);
392 $flipped = imagecreate($w, $h);
394 for ($x = 0; $x < $w; $x++) {
395 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
399 for ($y = 0; $y < $h; $y++) {
400 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
403 $this->image = $flipped;
407 * Fixes orientation and maybe returns EXIF data (?)
409 * @param string $filename Filename
412 public function orient(string $filename)
414 if ($this->isImagick()) {
415 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
416 $orientation = $this->image->getImageOrientation();
417 switch ($orientation) {
418 case Imagick::ORIENTATION_BOTTOMRIGHT:
419 $this->image->rotateimage("#000", 180);
421 case Imagick::ORIENTATION_RIGHTTOP:
422 $this->image->rotateimage("#000", 90);
424 case Imagick::ORIENTATION_LEFTBOTTOM:
425 $this->image->rotateimage("#000", -90);
429 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
432 // based off comment on http://php.net/manual/en/function.imagerotate.php
434 if (!$this->isValid()) {
438 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
442 $exif = @exif_read_data($filename, null, true);
447 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
453 case 2: // horizontal flip
457 case 3: // 180 rotate left
461 case 4: // vertical flip
462 $this->flip(false, true);
465 case 5: // vertical flip + 90 rotate right
466 $this->flip(false, true);
470 case 6: // 90 rotate right
474 case 7: // horizontal flip + 90 rotate right
479 case 8: // 90 rotate left
488 * Rescales image to minimum size
490 * @param integer $min Minimum dimension
493 public function scaleUp(int $min)
495 if (!$this->isValid()) {
499 $width = $this->getWidth();
500 $height = $this->getHeight();
502 if ((!$width)|| (!$height)) {
506 if ($width < $min && $height < $min) {
507 if ($width > $height) {
509 $dest_height = intval(($height * $min) / $width);
511 $dest_width = intval(($width * $min) / $height);
517 $dest_height = intval(($height * $min) / $width);
519 if ($height < $min) {
520 $dest_width = intval(($width * $min) / $height);
523 $dest_width = $width;
524 $dest_height = $height;
529 return $this->scale($dest_width, $dest_height);
533 * Scales image to square
535 * @param integer $dim Dimension
538 public function scaleToSquare(int $dim)
540 if (!$this->isValid()) {
544 return $this->scale($dim, $dim);
548 * Scale image to target dimensions
550 * @param int $dest_width Destination width
551 * @param int $dest_height Destination height
552 * @return boolean Success
554 private function scale(int $dest_width, int $dest_height): bool
556 if (!$this->isValid()) {
560 if ($this->isImagick()) {
562 * If it is not animated, there will be only one iteration here,
563 * so don't bother checking
565 // Don't forget to go back to the first frame
566 $this->image->setFirstIterator();
568 // FIXME - implement horizontal bias for scaling as in following GD functions
569 // to allow very tall images to be constrained only horizontally.
571 $this->image->scaleImage($dest_width, $dest_height);
572 } catch (Exception $e) {
573 // Imagick couldn't use the data
576 } while ($this->image->nextImage());
578 // These may not be necessary anymore
579 $this->width = $this->image->getImageWidth();
580 $this->height = $this->image->getImageHeight();
582 $dest = imagecreatetruecolor($dest_width, $dest_height);
583 imagealphablending($dest, false);
584 imagesavealpha($dest, true);
586 if ($this->type=='image/png') {
587 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
590 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
593 imagedestroy($this->image);
596 $this->image = $dest;
597 $this->width = imagesx($this->image);
598 $this->height = imagesy($this->image);
605 * Convert a GIF to a PNG to make it static
609 public function toStatic()
611 if ($this->type != 'image/gif') {
615 if ($this->isImagick()) {
616 $this->type == 'image/png';
617 $this->image->setFormat('png');
624 * @param integer $max maximum
625 * @param integer $x x coordinate
626 * @param integer $y y coordinate
627 * @param integer $w width
628 * @param integer $h height
631 public function crop(int $max, int $x, int $y, int $w, int $h)
633 if (!$this->isValid()) {
637 if ($this->isImagick()) {
638 $this->image->setFirstIterator();
640 $this->image->cropImage($w, $h, $x, $y);
642 * We need to remove the canva,
643 * or the image is not resized to the crop:
644 * http://php.net/manual/en/imagick.cropimage.php#97232
646 $this->image->setImagePage(0, 0, 0, 0);
647 } while ($this->image->nextImage());
648 return $this->scaleDown($max);
651 $dest = imagecreatetruecolor($max, $max);
652 imagealphablending($dest, false);
653 imagesavealpha($dest, true);
654 if ($this->type=='image/png') {
655 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
657 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
659 imagedestroy($this->image);
661 $this->image = $dest;
662 $this->width = imagesx($this->image);
663 $this->height = imagesy($this->image);
670 * Magic method allowing string casting of an Image object
672 * Ex: $data = $Image->asString();
674 * $data = (string) $Image;
677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679 public function __toString(): string
681 return (string) $this->asString();
685 * Returns image as string or false on failure
688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
690 public function asString()
692 if (!$this->isValid()) {
696 if ($this->isImagick()) {
699 $this->image = $this->image->deconstructImages();
700 return $this->image->getImagesBlob();
701 } catch (Exception $e) {
706 $stream = fopen('php://memory','r+');
708 // Enable interlacing
709 imageinterlace($this->image, true);
711 switch ($this->getType()) {
713 $quality = DI::config()->get('system', 'png_quality');
714 imagepng($this->image, $stream, $quality);
719 $quality = DI::config()->get('system', 'jpeg_quality');
720 imagejpeg($this->image, $stream, $quality);
724 return stream_get_contents($stream);
728 * Create a blurhash out of a given image string
730 * @param string $img_str
733 public function getBlurHash(): string
735 if ($this->isImagick()) {
736 // Imagick is not supported
740 $width = $this->getWidth();
741 $height = $this->getHeight();
743 if (max($width, $height) > 90) {
744 $this->scaleDown(90);
745 $width = $this->getWidth();
746 $height = $this->getHeight();
750 for ($y = 0; $y < $height; ++$y) {
752 for ($x = 0; $x < $width; ++$x) {
753 $index = imagecolorat($this->image, $x, $y);
754 $colors = imagecolorsforindex($this->image, $index);
756 $row[] = [$colors['red'], $colors['green'], $colors['blue']];
761 // The components define the amount of details (1 to 9).
765 return Blurhash::encode($pixels, $components_x, $components_y);
769 * Create an image out of a blurhash
771 * @param string $blurhash
772 * @param integer $width
773 * @param integer $height
776 public function getFromBlurHash(string $blurhash, int $width, int $height)
778 if ($this->isImagick()) {
779 // Imagick is not supported
783 $scaled = Images::getScalingDimensions($width, $height, 90);
784 $pixels = Blurhash::decode($blurhash, $scaled['width'], $scaled['height']);
786 $this->image = imagecreatetruecolor($scaled['width'], $scaled['height']);
787 for ($y = 0; $y < $scaled['height']; ++$y) {
788 for ($x = 0; $x < $scaled['width']; ++$x) {
789 [$r, $g, $b] = $pixels[$y][$x];
790 imagesetpixel($this->image, $x, $y, imagecolorallocate($this->image, $r, $g, $b));
794 $this->width = imagesx($this->image);
795 $this->height = imagesy($this->image);
798 $this->scaleUp(min($width, $height));