3 * @copyright Copyright (C) 2010-2023, 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))) {
69 $this->valid = !empty($data);
72 // Failed to load with Imagick, fallback
73 $this->imagick = false;
75 $this->loadData($data);
83 public function __destruct()
86 if ($this->isImagick()) {
87 $this->image->clear();
88 $this->image->destroy();
91 if (is_resource($this->image)) {
92 imagedestroy($this->image);
100 public function isImagick()
102 return $this->imagick;
106 * Loads image data into handler class
108 * @param string $data Image data
109 * @return boolean Success
110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
111 * @throws \ImagickException
113 private function loadData(string $data): bool
115 if ($this->isImagick()) {
116 $this->image = new Imagick();
118 $this->image->readImageBlob($data);
119 } catch (Exception $e) {
120 // Imagick couldn't use the data
125 * Setup the image to the format it will be saved to
127 $map = Images::getFormatsMap();
128 $format = $map[$this->type];
129 $this->image->setFormat($format);
131 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
133 $this->image = $this->image->coalesceImages();
134 } catch (Exception $e) {
139 * setup the compression here, so we'll do it only once
141 switch ($this->getType()) {
143 $quality = DI::config()->get('system', 'png_quality');
145 * From http://www.imagemagick.org/script/command-line-options.php#quality:
147 * 'For the MNG and PNG image formats, the quality value sets
148 * the zlib compression level (quality / 10) and filter-type (quality % 10).
149 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
150 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
152 $quality = $quality * 10;
153 $this->image->setCompressionQuality($quality);
158 $quality = DI::config()->get('system', 'jpeg_quality');
159 $this->image->setCompressionQuality($quality);
162 $this->width = $this->image->getImageWidth();
163 $this->height = $this->image->getImageHeight();
164 $this->valid = !empty($this->image);
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);
178 imageinterlace($this->image, true);
182 } catch (\Throwable $error) {
183 /** @see https://github.com/php/doc-en/commit/d09a881a8e9059d11e756ee59d75bf404d6941ed */
184 if (strstr($error->getMessage(), "gd-webp cannot allocate temporary buffer")) {
185 DI::logger()->notice('Image is probably animated and therefore unsupported', ['error' => $error]);
187 DI::logger()->warning('Unexpected throwable.', ['error' => $error]);
197 public function isValid(): bool
199 if ($this->isImagick()) {
200 return !empty($this->image);
208 public function getWidth()
210 if (!$this->isValid()) {
220 public function getHeight()
222 if (!$this->isValid()) {
226 return $this->height;
232 public function getImage()
234 if (!$this->isValid()) {
238 if ($this->isImagick()) {
241 $this->image = $this->image->deconstructImages();
243 } catch (Exception $e) {
253 public function getType()
255 if (!$this->isValid()) {
265 public function getExt()
267 if (!$this->isValid()) {
271 return $this->types[$this->getType()];
277 * @param integer $max max dimension
280 public function scaleDown(int $max)
282 if (!$this->isValid()) {
286 $width = $this->getWidth();
287 $height = $this->getHeight();
289 $scale = Images::getScalingDimensions($width, $height, $max);
291 return $this->scale($scale['width'], $scale['height']);
301 * @param integer $degrees degrees to rotate image
304 public function rotate(int $degrees)
306 if (!$this->isValid()) {
310 if ($this->isImagick()) {
311 $this->image->setFirstIterator();
313 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
314 } while ($this->image->nextImage());
316 $this->width = $this->image->getImageWidth();
317 $this->height = $this->image->getImageHeight();
321 // if script dies at this point check memory_limit setting in php.ini
322 $this->image = imagerotate($this->image, $degrees, 0);
323 $this->width = imagesx($this->image);
324 $this->height = imagesy($this->image);
330 * @param boolean $horiz optional, default true
331 * @param boolean $vert optional, default false
334 public function flip(bool $horiz = true, bool $vert = false)
336 if (!$this->isValid()) {
340 if ($this->isImagick()) {
341 $this->image->setFirstIterator();
344 $this->image->flipImage();
347 $this->image->flopImage();
349 } while ($this->image->nextImage());
353 $w = imagesx($this->image);
354 $h = imagesy($this->image);
355 $flipped = imagecreate($w, $h);
357 for ($x = 0; $x < $w; $x++) {
358 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
362 for ($y = 0; $y < $h; $y++) {
363 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
366 $this->image = $flipped;
370 * Fixes orientation and maybe returns EXIF data (?)
372 * @param string $filename Filename
375 public function orient(string $filename)
377 if ($this->isImagick()) {
378 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
379 $orientation = $this->image->getImageOrientation();
380 switch ($orientation) {
381 case Imagick::ORIENTATION_BOTTOMRIGHT:
384 case Imagick::ORIENTATION_RIGHTTOP:
387 case Imagick::ORIENTATION_LEFTBOTTOM:
392 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
395 // based off comment on http://php.net/manual/en/function.imagerotate.php
397 if (!$this->isValid()) {
401 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
405 $exif = @exif_read_data($filename, null, true);
410 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
416 case 2: // horizontal flip
420 case 3: // 180 rotate left
424 case 4: // vertical flip
425 $this->flip(false, true);
428 case 5: // vertical flip + 90 rotate right
429 $this->flip(false, true);
433 case 6: // 90 rotate right
437 case 7: // horizontal flip + 90 rotate right
442 case 8: // 90 rotate left
451 * Rescales image to minimum size
453 * @param integer $min Minimum dimension
456 public function scaleUp(int $min)
458 if (!$this->isValid()) {
462 $width = $this->getWidth();
463 $height = $this->getHeight();
465 if ((!$width)|| (!$height)) {
469 if ($width < $min && $height < $min) {
470 if ($width > $height) {
472 $dest_height = intval(($height * $min) / $width);
474 $dest_width = intval(($width * $min) / $height);
480 $dest_height = intval(($height * $min) / $width);
482 if ($height < $min) {
483 $dest_width = intval(($width * $min) / $height);
486 $dest_width = $width;
487 $dest_height = $height;
492 return $this->scale($dest_width, $dest_height);
496 * Scales image to square
498 * @param integer $dim Dimension
501 public function scaleToSquare(int $dim)
503 if (!$this->isValid()) {
507 return $this->scale($dim, $dim);
511 * Scale image to target dimensions
513 * @param int $dest_width Destination width
514 * @param int $dest_height Destination height
515 * @return boolean Success
517 private function scale(int $dest_width, int $dest_height): bool
519 if (!$this->isValid()) {
523 if ($this->isImagick()) {
525 * If it is not animated, there will be only one iteration here,
526 * so don't bother checking
528 // Don't forget to go back to the first frame
529 $this->image->setFirstIterator();
531 // FIXME - implement horizontal bias for scaling as in following GD functions
532 // to allow very tall images to be constrained only horizontally.
534 $this->image->scaleImage($dest_width, $dest_height);
535 } catch (Exception $e) {
536 // Imagick couldn't use the data
539 } while ($this->image->nextImage());
541 $this->width = $this->image->getImageWidth();
542 $this->height = $this->image->getImageHeight();
544 $dest = imagecreatetruecolor($dest_width, $dest_height);
545 imagealphablending($dest, false);
546 imagesavealpha($dest, true);
547 imageinterlace($dest, true);
549 if ($this->type=='image/png') {
550 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
553 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
556 imagedestroy($this->image);
559 $this->image = $dest;
560 $this->width = imagesx($this->image);
561 $this->height = imagesy($this->image);
568 * Convert a GIF to a PNG to make it static
572 public function toStatic()
574 if ($this->type != 'image/gif') {
578 if ($this->isImagick()) {
579 $this->type == 'image/png';
580 $this->image->setFormat('png');
587 * @param integer $max maximum
588 * @param integer $x x coordinate
589 * @param integer $y y coordinate
590 * @param integer $w width
591 * @param integer $h height
594 public function crop(int $max, int $x, int $y, int $w, int $h)
596 if (!$this->isValid()) {
600 if ($this->isImagick()) {
601 $this->image->setFirstIterator();
603 $this->image->cropImage($w, $h, $x, $y);
605 * We need to remove the canvas,
606 * or the image is not resized to the crop:
607 * http://php.net/manual/en/imagick.cropimage.php#97232
609 $this->image->setImagePage(0, 0, 0, 0);
610 } while ($this->image->nextImage());
611 return $this->scaleDown($max);
614 $dest = imagecreatetruecolor($max, $max);
615 imagealphablending($dest, false);
616 imagesavealpha($dest, true);
617 imageinterlace($dest, true);
618 if ($this->type=='image/png') {
619 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
621 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
623 imagedestroy($this->image);
625 $this->image = $dest;
626 $this->width = imagesx($this->image);
627 $this->height = imagesy($this->image);
634 * Magic method allowing string casting of an Image object
636 * Ex: $data = $Image->asString();
638 * $data = (string) $Image;
641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
643 public function __toString(): string
645 return (string) $this->asString();
649 * Returns image as string or false on failure
652 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
654 public function asString()
656 if (!$this->isValid()) {
660 if ($this->isImagick()) {
663 $this->image = $this->image->deconstructImages();
664 return $this->image->getImagesBlob();
665 } catch (Exception $e) {
670 $stream = fopen('php://memory','r+');
672 // Enable interlacing
673 imageinterlace($this->image, true);
675 switch ($this->getType()) {
677 $quality = DI::config()->get('system', 'png_quality');
678 imagepng($this->image, $stream, $quality);
683 $quality = DI::config()->get('system', 'jpeg_quality');
684 imagejpeg($this->image, $stream, $quality);
688 return stream_get_contents($stream);
692 * Create a blurhash out of a given image string
694 * @param string $img_str
697 public function getBlurHash(): string
699 $image = New Image($this->asString());
700 if (empty($image) || !$this->isValid()) {
704 $width = $image->getWidth();
705 $height = $image->getHeight();
707 if (max($width, $height) > 90) {
708 $image->scaleDown(90);
709 $width = $image->getWidth();
710 $height = $image->getHeight();
713 if (empty($width) || empty($height)) {
718 for ($y = 0; $y < $height; ++$y) {
720 for ($x = 0; $x < $width; ++$x) {
721 if ($image->isImagick()) {
723 $colors = $image->image->getImagePixelColor($x, $y)->getColor();
724 } catch (\Exception $exception) {
727 $row[] = [$colors['r'], $colors['g'], $colors['b']];
729 $index = imagecolorat($image->image, $x, $y);
730 $colors = @imagecolorsforindex($image->image, $index);
731 $row[] = [$colors['red'], $colors['green'], $colors['blue']];
737 // The components define the amount of details (1 to 9).
741 return Blurhash::encode($pixels, $components_x, $components_y);
745 * Create an image out of a blurhash
747 * @param string $blurhash
748 * @param integer $width
749 * @param integer $height
752 public function getFromBlurHash(string $blurhash, int $width, int $height)
754 $scaled = Images::getScalingDimensions($width, $height, 90);
755 $pixels = Blurhash::decode($blurhash, $scaled['width'], $scaled['height']);
757 if ($this->isImagick()) {
758 $this->image = new Imagick();
759 $draw = new ImagickDraw();
760 $this->image->newImage($scaled['width'], $scaled['height'], '', 'png');
762 $this->image = imagecreatetruecolor($scaled['width'], $scaled['height']);
765 for ($y = 0; $y < $scaled['height']; ++$y) {
766 for ($x = 0; $x < $scaled['width']; ++$x) {
767 [$r, $g, $b] = $pixels[$y][$x];
768 if ($this->isImagick()) {
769 $draw->setFillColor("rgb($r, $g, $b)");
770 $draw->point($x, $y);
772 imagesetpixel($this->image, $x, $y, imagecolorallocate($this->image, $r, $g, $b));
777 if ($this->isImagick()) {
778 $this->image->drawImage($draw);
779 $this->width = $this->image->getImageWidth();
780 $this->height = $this->image->getImageHeight();
782 $this->width = imagesx($this->image);
783 $this->height = imagesy($this->image);
786 $this->valid = !empty($this->image);
788 $this->scaleUp(min($width, $height));