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);
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 !empty($this->image);
207 public function getWidth()
209 if (!$this->isValid()) {
219 public function getHeight()
221 if (!$this->isValid()) {
225 return $this->height;
231 public function getImage()
233 if (!$this->isValid()) {
237 if ($this->isImagick()) {
240 $this->image = $this->image->deconstructImages();
242 } catch (Exception $e) {
252 public function getType()
254 if (!$this->isValid()) {
264 public function getExt()
266 if (!$this->isValid()) {
270 return $this->types[$this->getType()];
276 * @param integer $max max dimension
279 public function scaleDown(int $max)
281 if (!$this->isValid()) {
285 $width = $this->getWidth();
286 $height = $this->getHeight();
288 $scale = Images::getScalingDimensions($width, $height, $max);
290 return $this->scale($scale['width'], $scale['height']);
300 * @param integer $degrees degrees to rotate image
303 public function rotate(int $degrees)
305 if (!$this->isValid()) {
309 if ($this->isImagick()) {
310 $this->image->setFirstIterator();
312 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
313 } while ($this->image->nextImage());
315 $this->width = $this->image->getImageWidth();
316 $this->height = $this->image->getImageHeight();
320 // if script dies at this point check memory_limit setting in php.ini
321 $this->image = imagerotate($this->image, $degrees, 0);
322 $this->width = imagesx($this->image);
323 $this->height = imagesy($this->image);
329 * @param boolean $horiz optional, default true
330 * @param boolean $vert optional, default false
333 public function flip(bool $horiz = true, bool $vert = false)
335 if (!$this->isValid()) {
339 if ($this->isImagick()) {
340 $this->image->setFirstIterator();
343 $this->image->flipImage();
346 $this->image->flopImage();
348 } while ($this->image->nextImage());
352 $w = imagesx($this->image);
353 $h = imagesy($this->image);
354 $flipped = imagecreate($w, $h);
356 for ($x = 0; $x < $w; $x++) {
357 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
361 for ($y = 0; $y < $h; $y++) {
362 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
365 $this->image = $flipped;
369 * Fixes orientation and maybe returns EXIF data (?)
371 * @param string $filename Filename
374 public function orient(string $filename)
376 if ($this->isImagick()) {
377 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
378 $orientation = $this->image->getImageOrientation();
379 switch ($orientation) {
380 case Imagick::ORIENTATION_BOTTOMRIGHT:
383 case Imagick::ORIENTATION_RIGHTTOP:
386 case Imagick::ORIENTATION_LEFTBOTTOM:
391 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
394 // based off comment on http://php.net/manual/en/function.imagerotate.php
396 if (!$this->isValid()) {
400 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
404 $exif = @exif_read_data($filename, null, true);
409 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
415 case 2: // horizontal flip
419 case 3: // 180 rotate left
423 case 4: // vertical flip
424 $this->flip(false, true);
427 case 5: // vertical flip + 90 rotate right
428 $this->flip(false, true);
432 case 6: // 90 rotate right
436 case 7: // horizontal flip + 90 rotate right
441 case 8: // 90 rotate left
450 * Rescales image to minimum size
452 * @param integer $min Minimum dimension
455 public function scaleUp(int $min)
457 if (!$this->isValid()) {
461 $width = $this->getWidth();
462 $height = $this->getHeight();
464 if ((!$width)|| (!$height)) {
468 if ($width < $min && $height < $min) {
469 if ($width > $height) {
471 $dest_height = intval(($height * $min) / $width);
473 $dest_width = intval(($width * $min) / $height);
479 $dest_height = intval(($height * $min) / $width);
481 if ($height < $min) {
482 $dest_width = intval(($width * $min) / $height);
485 $dest_width = $width;
486 $dest_height = $height;
491 return $this->scale($dest_width, $dest_height);
495 * Scales image to square
497 * @param integer $dim Dimension
500 public function scaleToSquare(int $dim)
502 if (!$this->isValid()) {
506 return $this->scale($dim, $dim);
510 * Scale image to target dimensions
512 * @param int $dest_width Destination width
513 * @param int $dest_height Destination height
514 * @return boolean Success
516 private function scale(int $dest_width, int $dest_height): bool
518 if (!$this->isValid()) {
522 if ($this->isImagick()) {
524 * If it is not animated, there will be only one iteration here,
525 * so don't bother checking
527 // Don't forget to go back to the first frame
528 $this->image->setFirstIterator();
530 // FIXME - implement horizontal bias for scaling as in following GD functions
531 // to allow very tall images to be constrained only horizontally.
533 $this->image->scaleImage($dest_width, $dest_height);
534 } catch (Exception $e) {
535 // Imagick couldn't use the data
538 } while ($this->image->nextImage());
540 $this->width = $this->image->getImageWidth();
541 $this->height = $this->image->getImageHeight();
543 $dest = imagecreatetruecolor($dest_width, $dest_height);
544 imagealphablending($dest, false);
545 imagesavealpha($dest, true);
547 if ($this->type=='image/png') {
548 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
551 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
554 imagedestroy($this->image);
557 $this->image = $dest;
558 $this->width = imagesx($this->image);
559 $this->height = imagesy($this->image);
566 * Convert a GIF to a PNG to make it static
570 public function toStatic()
572 if ($this->type != 'image/gif') {
576 if ($this->isImagick()) {
577 $this->type == 'image/png';
578 $this->image->setFormat('png');
585 * @param integer $max maximum
586 * @param integer $x x coordinate
587 * @param integer $y y coordinate
588 * @param integer $w width
589 * @param integer $h height
592 public function crop(int $max, int $x, int $y, int $w, int $h)
594 if (!$this->isValid()) {
598 if ($this->isImagick()) {
599 $this->image->setFirstIterator();
601 $this->image->cropImage($w, $h, $x, $y);
603 * We need to remove the canvas,
604 * or the image is not resized to the crop:
605 * http://php.net/manual/en/imagick.cropimage.php#97232
607 $this->image->setImagePage(0, 0, 0, 0);
608 } while ($this->image->nextImage());
609 return $this->scaleDown($max);
612 $dest = imagecreatetruecolor($max, $max);
613 imagealphablending($dest, false);
614 imagesavealpha($dest, true);
615 if ($this->type=='image/png') {
616 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
618 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
620 imagedestroy($this->image);
622 $this->image = $dest;
623 $this->width = imagesx($this->image);
624 $this->height = imagesy($this->image);
631 * Magic method allowing string casting of an Image object
633 * Ex: $data = $Image->asString();
635 * $data = (string) $Image;
638 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
640 public function __toString(): string
642 return (string) $this->asString();
646 * Returns image as string or false on failure
649 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
651 public function asString()
653 if (!$this->isValid()) {
657 if ($this->isImagick()) {
660 $this->image = $this->image->deconstructImages();
661 return $this->image->getImagesBlob();
662 } catch (Exception $e) {
667 $stream = fopen('php://memory','r+');
669 // Enable interlacing
670 imageinterlace($this->image, true);
672 switch ($this->getType()) {
674 $quality = DI::config()->get('system', 'png_quality');
675 imagepng($this->image, $stream, $quality);
680 $quality = DI::config()->get('system', 'jpeg_quality');
681 imagejpeg($this->image, $stream, $quality);
685 return stream_get_contents($stream);
689 * Create a blurhash out of a given image string
691 * @param string $img_str
694 public function getBlurHash(): string
696 $image = New Image($this->asString());
697 if (empty($image) || !$this->isValid()) {
701 $width = $image->getWidth();
702 $height = $image->getHeight();
704 if (max($width, $height) > 90) {
705 $image->scaleDown(90);
706 $width = $image->getWidth();
707 $height = $image->getHeight();
710 if (empty($width) || empty($height)) {
715 for ($y = 0; $y < $height; ++$y) {
717 for ($x = 0; $x < $width; ++$x) {
718 if ($image->isImagick()) {
720 $colors = $image->image->getImagePixelColor($x, $y)->getColor();
721 } catch (\Exception $exception) {
724 $row[] = [$colors['r'], $colors['g'], $colors['b']];
726 $index = imagecolorat($image->image, $x, $y);
727 $colors = @imagecolorsforindex($image->image, $index);
728 $row[] = [$colors['red'], $colors['green'], $colors['blue']];
734 // The components define the amount of details (1 to 9).
738 return Blurhash::encode($pixels, $components_x, $components_y);
742 * Create an image out of a blurhash
744 * @param string $blurhash
745 * @param integer $width
746 * @param integer $height
749 public function getFromBlurHash(string $blurhash, int $width, int $height)
751 $scaled = Images::getScalingDimensions($width, $height, 90);
752 $pixels = Blurhash::decode($blurhash, $scaled['width'], $scaled['height']);
754 if ($this->isImagick()) {
755 $this->image = new Imagick();
756 $draw = new ImagickDraw();
757 $this->image->newImage($scaled['width'], $scaled['height'], '', 'png');
759 $this->image = imagecreatetruecolor($scaled['width'], $scaled['height']);
762 for ($y = 0; $y < $scaled['height']; ++$y) {
763 for ($x = 0; $x < $scaled['width']; ++$x) {
764 [$r, $g, $b] = $pixels[$y][$x];
765 if ($this->isImagick()) {
766 $draw->setFillColor("rgb($r, $g, $b)");
767 $draw->point($x, $y);
769 imagesetpixel($this->image, $x, $y, imagecolorallocate($this->image, $r, $g, $b));
774 if ($this->isImagick()) {
775 $this->image->drawImage($draw);
776 $this->width = $this->image->getImageWidth();
777 $this->height = $this->image->getImageHeight();
779 $this->width = imagesx($this->image);
780 $this->height = imagesy($this->image);
783 $this->valid = !empty($this->image);
785 $this->scaleUp(min($width, $height));