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 * Class to handle images
35 /** @var Imagick|resource */
39 * Put back gd stuff, not everybody have Imagick
51 * @param boolean $type optional, default null
52 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
53 * @throws \ImagickException
55 public function __construct($data, $type = null)
57 $this->imagick = class_exists('Imagick');
58 $this->types = Images::supportedTypes();
59 if (!array_key_exists($type, $this->types)) {
64 if ($this->isImagick() && $this->loadData($data)) {
67 // Failed to load with Imagick, fallback
68 $this->imagick = false;
70 return $this->loadData($data);
78 public function __destruct()
81 if ($this->isImagick()) {
82 $this->image->clear();
83 $this->image->destroy();
86 if (is_resource($this->image)) {
87 imagedestroy($this->image);
95 public function isImagick()
97 return $this->imagick;
101 * @param string $data data
103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
104 * @throws \ImagickException
106 private function loadData($data)
108 if ($this->isImagick()) {
109 $this->image = new Imagick();
111 $this->image->readImageBlob($data);
112 } catch (Exception $e) {
113 // Imagick couldn't use the data
118 * Setup the image to the format it will be saved to
120 $map = Images::getFormatsMap();
121 $format = $map[$this->type];
122 $this->image->setFormat($format);
124 // Always coalesce, if it is not a multi-frame image it won't hurt anyway
126 $this->image = $this->image->coalesceImages();
127 } catch (Exception $e) {
132 * setup the compression here, so we'll do it only once
134 switch ($this->getType()) {
136 $quality = DI::config()->get('system', 'png_quality');
138 * From http://www.imagemagick.org/script/command-line-options.php#quality:
140 * 'For the MNG and PNG image formats, the quality value sets
141 * the zlib compression level (quality / 10) and filter-type (quality % 10).
142 * The default PNG "quality" is 75, which means compression level 7 with adaptive PNG filtering,
143 * unless the image has a color map, in which case it means compression level 7 with no PNG filtering'
145 $quality = $quality * 10;
146 $this->image->setCompressionQuality($quality);
149 $quality = DI::config()->get('system', 'jpeg_quality');
150 $this->image->setCompressionQuality($quality);
153 // The 'width' and 'height' properties are only used by non-Imagick routines.
154 $this->width = $this->image->getImageWidth();
155 $this->height = $this->image->getImageHeight();
161 $this->valid = false;
162 $this->image = @imagecreatefromstring($data);
163 if ($this->image !== false) {
164 $this->width = imagesx($this->image);
165 $this->height = imagesy($this->image);
167 imagealphablending($this->image, false);
168 imagesavealpha($this->image, true);
179 public function isValid()
181 if ($this->isImagick()) {
182 return ($this->image !== false);
190 public function getWidth()
192 if (!$this->isValid()) {
196 if ($this->isImagick()) {
197 return $this->image->getImageWidth();
205 public function getHeight()
207 if (!$this->isValid()) {
211 if ($this->isImagick()) {
212 return $this->image->getImageHeight();
214 return $this->height;
220 public function getImage()
222 if (!$this->isValid()) {
226 if ($this->isImagick()) {
229 $this->image = $this->image->deconstructImages();
231 } catch (Exception $e) {
241 public function getType()
243 if (!$this->isValid()) {
253 public function getExt()
255 if (!$this->isValid()) {
259 return $this->types[$this->getType()];
263 * @param integer $max max dimension
266 public function scaleDown($max)
268 if (!$this->isValid()) {
272 $width = $this->getWidth();
273 $height = $this->getHeight();
275 if ((! $width)|| (! $height)) {
279 if ($width > $max && $height > $max) {
280 // very tall image (greater than 16:9)
281 // constrain the width - let the height float.
283 if ((($height * 9) / 16) > $width) {
285 $dest_height = intval(($height * $max) / $width);
286 } elseif ($width > $height) {
287 // else constrain both dimensions
289 $dest_height = intval(($height * $max) / $width);
291 $dest_width = intval(($width * $max) / $height);
297 $dest_height = intval(($height * $max) / $width);
299 if ($height > $max) {
300 // very tall image (greater than 16:9)
301 // but width is OK - don't do anything
303 if ((($height * 9) / 16) > $width) {
304 $dest_width = $width;
305 $dest_height = $height;
307 $dest_width = intval(($width * $max) / $height);
311 $dest_width = $width;
312 $dest_height = $height;
317 return $this->scale($dest_width, $dest_height);
321 * @param integer $degrees degrees to rotate image
324 public function rotate($degrees)
326 if (!$this->isValid()) {
330 if ($this->isImagick()) {
331 $this->image->setFirstIterator();
333 $this->image->rotateImage(new ImagickPixel(), -$degrees); // ImageMagick rotates in the opposite direction of imagerotate()
334 } while ($this->image->nextImage());
338 // if script dies at this point check memory_limit setting in php.ini
339 $this->image = imagerotate($this->image, $degrees, 0);
340 $this->width = imagesx($this->image);
341 $this->height = imagesy($this->image);
345 * @param boolean $horiz optional, default true
346 * @param boolean $vert optional, default false
349 public function flip($horiz = true, $vert = false)
351 if (!$this->isValid()) {
355 if ($this->isImagick()) {
356 $this->image->setFirstIterator();
359 $this->image->flipImage();
362 $this->image->flopImage();
364 } while ($this->image->nextImage());
368 $w = imagesx($this->image);
369 $h = imagesy($this->image);
370 $flipped = imagecreate($w, $h);
372 for ($x = 0; $x < $w; $x++) {
373 imagecopy($flipped, $this->image, $x, 0, $w - $x - 1, 0, 1, $h);
377 for ($y = 0; $y < $h; $y++) {
378 imagecopy($flipped, $this->image, 0, $y, 0, $h - $y - 1, $w, 1);
381 $this->image = $flipped;
385 * @param string $filename filename
388 public function orient($filename)
390 if ($this->isImagick()) {
391 // based off comment on http://php.net/manual/en/imagick.getimageorientation.php
392 $orientation = $this->image->getImageOrientation();
393 switch ($orientation) {
394 case Imagick::ORIENTATION_BOTTOMRIGHT:
395 $this->image->rotateimage("#000", 180);
397 case Imagick::ORIENTATION_RIGHTTOP:
398 $this->image->rotateimage("#000", 90);
400 case Imagick::ORIENTATION_LEFTBOTTOM:
401 $this->image->rotateimage("#000", -90);
405 $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
408 // based off comment on http://php.net/manual/en/function.imagerotate.php
410 if (!$this->isValid()) {
414 if ((!function_exists('exif_read_data')) || ($this->getType() !== 'image/jpeg')) {
418 $exif = @exif_read_data($filename, null, true);
423 $ort = isset($exif['IFD0']['Orientation']) ? $exif['IFD0']['Orientation'] : 1;
429 case 2: // horizontal flip
433 case 3: // 180 rotate left
437 case 4: // vertical flip
438 $this->flip(false, true);
441 case 5: // vertical flip + 90 rotate right
442 $this->flip(false, true);
446 case 6: // 90 rotate right
450 case 7: // horizontal flip + 90 rotate right
455 case 8: // 90 rotate left
464 * @param integer $min minimum dimension
467 public function scaleUp($min)
469 if (!$this->isValid()) {
473 $width = $this->getWidth();
474 $height = $this->getHeight();
476 if ((!$width)|| (!$height)) {
480 if ($width < $min && $height < $min) {
481 if ($width > $height) {
483 $dest_height = intval(($height * $min) / $width);
485 $dest_width = intval(($width * $min) / $height);
491 $dest_height = intval(($height * $min) / $width);
493 if ($height < $min) {
494 $dest_width = intval(($width * $min) / $height);
497 $dest_width = $width;
498 $dest_height = $height;
503 return $this->scale($dest_width, $dest_height);
507 * @param integer $dim dimension
510 public function scaleToSquare($dim)
512 if (!$this->isValid()) {
516 return $this->scale($dim, $dim);
520 * Scale image to target dimensions
522 * @param int $dest_width
523 * @param int $dest_height
526 private function scale($dest_width, $dest_height)
528 if (!$this->isValid()) {
532 if ($this->isImagick()) {
534 * If it is not animated, there will be only one iteration here,
535 * so don't bother checking
537 // Don't forget to go back to the first frame
538 $this->image->setFirstIterator();
540 // FIXME - implement horizontal bias for scaling as in following GD functions
541 // to allow very tall images to be constrained only horizontally.
543 $this->image->scaleImage($dest_width, $dest_height);
544 } catch (Exception $e) {
545 // Imagick couldn't use the data
548 } while ($this->image->nextImage());
550 // These may not be necessary anymore
551 $this->width = $this->image->getImageWidth();
552 $this->height = $this->image->getImageHeight();
554 $dest = imagecreatetruecolor($dest_width, $dest_height);
555 imagealphablending($dest, false);
556 imagesavealpha($dest, true);
558 if ($this->type=='image/png') {
559 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
562 imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $dest_width, $dest_height, $this->width, $this->height);
565 imagedestroy($this->image);
568 $this->image = $dest;
569 $this->width = imagesx($this->image);
570 $this->height = imagesy($this->image);
577 * Convert a GIF to a PNG to make it static
579 public function toStatic()
581 if ($this->type != 'image/gif') {
585 if ($this->isImagick()) {
586 $this->type == 'image/png';
587 $this->image->setFormat('png');
592 * @param integer $max maximum
593 * @param integer $x x coordinate
594 * @param integer $y y coordinate
595 * @param integer $w width
596 * @param integer $h height
599 public function crop($max, $x, $y, $w, $h)
601 if (!$this->isValid()) {
605 if ($this->isImagick()) {
606 $this->image->setFirstIterator();
608 $this->image->cropImage($w, $h, $x, $y);
610 * We need to remove the canva,
611 * or the image is not resized to the crop:
612 * http://php.net/manual/en/imagick.cropimage.php#97232
614 $this->image->setImagePage(0, 0, 0, 0);
615 } while ($this->image->nextImage());
616 return $this->scaleDown($max);
619 $dest = imagecreatetruecolor($max, $max);
620 imagealphablending($dest, false);
621 imagesavealpha($dest, true);
622 if ($this->type=='image/png') {
623 imagefill($dest, 0, 0, imagecolorallocatealpha($dest, 0, 0, 0, 127)); // fill with alpha
625 imagecopyresampled($dest, $this->image, 0, 0, $x, $y, $max, $max, $w, $h);
627 imagedestroy($this->image);
629 $this->image = $dest;
630 $this->width = imagesx($this->image);
631 $this->height = imagesy($this->image);
635 * Magic method allowing string casting of an Image object
637 * Ex: $data = $Image->asString();
639 * $data = (string) $Image;
642 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
644 public function __toString() {
645 return $this->asString();
650 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
652 public function asString()
654 if (!$this->isValid()) {
658 if ($this->isImagick()) {
661 $this->image = $this->image->deconstructImages();
662 $string = $this->image->getImagesBlob();
664 } catch (Exception $e) {
671 // Enable interlacing
672 imageinterlace($this->image, true);
674 switch ($this->getType()) {
676 $quality = DI::config()->get('system', 'png_quality');
677 imagepng($this->image, null, $quality);
680 $quality = DI::config()->get('system', 'jpeg_quality');
681 imagejpeg($this->image, null, $quality);
683 $string = ob_get_contents();