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))) {
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 ($this->image !== false);
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 if ((! $width)|| (! $height)) {
292 if ($width > $max && $height > $max) {
293 // very tall image (greater than 16:9)
294 // constrain the width - let the height float.
296 if ((($height * 9) / 16) > $width) {
298 $dest_height = intval(($height * $max) / $width);
299 } elseif ($width > $height) {
300 // else constrain both dimensions
302 $dest_height = intval(($height * $max) / $width);
304 $dest_width = intval(($width * $max) / $height);
310 $dest_height = intval(($height * $max) / $width);
312 if ($height > $max) {
313 // very tall image (greater than 16:9)
314 // but width is OK - don't do anything
316 if ((($height * 9) / 16) > $width) {
317 $dest_width = $width;
318 $dest_height = $height;
320 $dest_width = intval(($width * $max) / $height);
324 $dest_width = $width;
325 $dest_height = $height;
330 return $this->scale($dest_width, $dest_height);
336 * @param integer $degrees degrees to rotate image
339 public function rotate(int $degrees)
341 if (!$this->isValid()) {
345 if ($this->isImagick()) {
346 $this->image->setFirstIterator();
348 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
349 } while ($this->image->nextImage());
351 $this->width = $this->image->getImageWidth();
352 $this->height = $this->image->getImageHeight();
356 // if script dies at this point check memory_limit setting in php.ini
357 $this->image = imagerotate($this->image, $degrees, 0);
358 $this->width = imagesx($this->image);
359 $this->height = imagesy($this->image);
365 * @param boolean $horiz optional, default true
366 * @param boolean $vert optional, default false
369 public function flip(bool $horiz = true, bool $vert = false)
371 if (!$this->isValid()) {
375 if ($this->isImagick()) {
376 $this->image->setFirstIterator();
379 $this->image->flipImage();
382 $this->image->flopImage();
384 } while ($this->image->nextImage());
388 $w = imagesx($this->image);
389 $h = imagesy($this->image);
390 $flipped = imagecreate($w, $h);
392 for ($x = 0; $x < $w; $x++) {
393 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
397 for ($y = 0; $y < $h; $y++) {
398 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
401 $this->image = $flipped;
405 * Fixes orientation and maybe returns EXIF data (?)
407 * @param string $filename Filename
410 public function orient(string $filename)
412 if ($this->isImagick()) {
413 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
414 $orientation = $this->image->getImageOrientation();
415 switch ($orientation) {
416 case Imagick::ORIENTATION_BOTTOMRIGHT:
417 $this->image->rotateimage("#000", 180);
419 case Imagick::ORIENTATION_RIGHTTOP:
420 $this->image->rotateimage("#000", 90);
422 case Imagick::ORIENTATION_LEFTBOTTOM:
423 $this->image->rotateimage("#000", -90);
427 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
430 // based off comment on http://php.net/manual/en/function.imagerotate.php
432 if (!$this->isValid()) {
436 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
440 $exif = @exif_read_data($filename, null, true);
445 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
451 case 2: // horizontal flip
455 case 3: // 180 rotate left
459 case 4: // vertical flip
460 $this->flip(false, true);
463 case 5: // vertical flip + 90 rotate right
464 $this->flip(false, true);
468 case 6: // 90 rotate right
472 case 7: // horizontal flip + 90 rotate right
477 case 8: // 90 rotate left
486 * Rescales image to minimum size
488 * @param integer $min Minimum dimension
491 public function scaleUp(int $min)
493 if (!$this->isValid()) {
497 $width = $this->getWidth();
498 $height = $this->getHeight();
500 if ((!$width)|| (!$height)) {
504 if ($width < $min && $height < $min) {
505 if ($width > $height) {
507 $dest_height = intval(($height * $min) / $width);
509 $dest_width = intval(($width * $min) / $height);
515 $dest_height = intval(($height * $min) / $width);
517 if ($height < $min) {
518 $dest_width = intval(($width * $min) / $height);
521 $dest_width = $width;
522 $dest_height = $height;
527 return $this->scale($dest_width, $dest_height);
531 * Scales image to square
533 * @param integer $dim Dimension
536 public function scaleToSquare(int $dim)
538 if (!$this->isValid()) {
542 return $this->scale($dim, $dim);
546 * Scale image to target dimensions
548 * @param int $dest_width Destination width
549 * @param int $dest_height Destination height
550 * @return boolean Success
552 private function scale(int $dest_width, int $dest_height): bool
554 if (!$this->isValid()) {
558 if ($this->isImagick()) {
560 * If it is not animated, there will be only one iteration here,
561 * so don't bother checking
563 // Don't forget to go back to the first frame
564 $this->image->setFirstIterator();
566 // FIXME - implement horizontal bias for scaling as in following GD functions
567 // to allow very tall images to be constrained only horizontally.
569 $this->image->scaleImage($dest_width, $dest_height);
570 } catch (Exception $e) {
571 // Imagick couldn't use the data
574 } while ($this->image->nextImage());
576 $this->width = $this->image->getImageWidth();
577 $this->height = $this->image->getImageHeight();
579 $dest = imagecreatetruecolor($dest_width, $dest_height);
580 imagealphablending($dest, false);
581 imagesavealpha($dest, true);
583 if ($this->type=='image/png') {
584 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
587 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
590 imagedestroy($this->image);
593 $this->image = $dest;
594 $this->width = imagesx($this->image);
595 $this->height = imagesy($this->image);
602 * Convert a GIF to a PNG to make it static
606 public function toStatic()
608 if ($this->type != 'image/gif') {
612 if ($this->isImagick()) {
613 $this->type == 'image/png';
614 $this->image->setFormat('png');
621 * @param integer $max maximum
622 * @param integer $x x coordinate
623 * @param integer $y y coordinate
624 * @param integer $w width
625 * @param integer $h height
628 public function crop(int $max, int $x, int $y, int $w, int $h)
630 if (!$this->isValid()) {
634 if ($this->isImagick()) {
635 $this->image->setFirstIterator();
637 $this->image->cropImage($w, $h, $x, $y);
639 * We need to remove the canva,
640 * or the image is not resized to the crop:
641 * http://php.net/manual/en/imagick.cropimage.php#97232
643 $this->image->setImagePage(0, 0, 0, 0);
644 } while ($this->image->nextImage());
645 return $this->scaleDown($max);
648 $dest = imagecreatetruecolor($max, $max);
649 imagealphablending($dest, false);
650 imagesavealpha($dest, true);
651 if ($this->type=='image/png') {
652 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
654 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
656 imagedestroy($this->image);
658 $this->image = $dest;
659 $this->width = imagesx($this->image);
660 $this->height = imagesy($this->image);
667 * Magic method allowing string casting of an Image object
669 * Ex: $data = $Image->asString();
671 * $data = (string) $Image;
674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
676 public function __toString(): string
678 return (string) $this->asString();
682 * Returns image as string or false on failure
685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
687 public function asString()
689 if (!$this->isValid()) {
693 if ($this->isImagick()) {
696 $this->image = $this->image->deconstructImages();
697 return $this->image->getImagesBlob();
698 } catch (Exception $e) {
703 $stream = fopen('php://memory','r+');
705 // Enable interlacing
706 imageinterlace($this->image, true);
708 switch ($this->getType()) {
710 $quality = DI::config()->get('system', 'png_quality');
711 imagepng($this->image, $stream, $quality);
716 $quality = DI::config()->get('system', 'jpeg_quality');
717 imagejpeg($this->image, $stream, $quality);
721 return stream_get_contents($stream);
725 * Create a blurhash out of a given image string
727 * @param string $img_str
730 public function getBlurHash(): string
732 $image = New Image($this->asString());
733 if (empty($image) || !$this->isValid()) {
737 $width = $image->getWidth();
738 $height = $image->getHeight();
740 if (max($width, $height) > 90) {
741 $image->scaleDown(90);
742 $width = $image->getWidth();
743 $height = $image->getHeight();
747 for ($y = 0; $y < $height; ++$y) {
749 for ($x = 0; $x < $width; ++$x) {
750 if ($image->isImagick()) {
752 $colors = $image->image->getImagePixelColor($x, $y)->getColor();
753 } catch (\Throwable $th) {
756 $row[] = [$colors['r'], $colors['g'], $colors['b']];
758 $index = imagecolorat($image->image, $x, $y);
759 $colors = @imagecolorsforindex($image->image, $index);
760 $row[] = [$colors['red'], $colors['green'], $colors['blue']];
766 // The components define the amount of details (1 to 9).
770 return Blurhash::encode($pixels, $components_x, $components_y);
774 * Create an image out of a blurhash
776 * @param string $blurhash
777 * @param integer $width
778 * @param integer $height
781 public function getFromBlurHash(string $blurhash, int $width, int $height)
783 $scaled = Images::getScalingDimensions($width, $height, 90);
784 $pixels = Blurhash::decode($blurhash, $scaled['width'], $scaled['height']);
786 if ($this->isImagick()) {
787 $this->image = new Imagick();
788 $draw = new ImagickDraw();
789 $this->image->newImage($scaled['width'], $scaled['height'], '', 'png');
791 $this->image = imagecreatetruecolor($scaled['width'], $scaled['height']);
794 for ($y = 0; $y < $scaled['height']; ++$y) {
795 for ($x = 0; $x < $scaled['width']; ++$x) {
796 [$r, $g, $b] = $pixels[$y][$x];
797 if ($this->isImagick()) {
798 $draw->setFillColor("rgb($r, $g, $b)");
799 $draw->point($x, $y);
801 imagesetpixel($this->image, $x, $y, imagecolorallocate($this->image, $r, $g, $b));
806 if ($this->isImagick()) {
807 $this->image->drawImage($draw);
808 $this->width = $this->image->getImageWidth();
809 $this->height = $this->image->getImageHeight();
811 $this->width = imagesx($this->image);
812 $this->height = imagesy($this->image);
815 $this->valid = !empty($this->image);
817 $this->scaleUp(min($width, $height));