@param resource $img GD image

@return array

@throws \Exception
423110
private static function getImageSize($img)
    {
        $width  = imagesx($img);
        $height = imagesy($img);
        if ( ! $width || ! $height) {
            throw new \Exception('can`t create thumbnail: can`t get image size, invalid image width or height');
        }

        return [$width, $height];
    }
597573
public function resize($img, $size)
    {
        $curSize = imagesx($img);
        if ($curSize == $size) {
            return $img;
        }

        $newImg = imagecreatetruecolor($size, $size);
        imagecopyresampled($newImg, $img, 0, 0, 0, 0, $size, $size, $curSize, $curSize);

        return $newImg;
    }
365609
protected function _convert_gif_to_png($image_url) {
		if ( !function_exists("imagecreatefromgif") ) {
			throw new DOMPDF_Exception("Function imagecreatefromgif() not found.  Cannot convert gif image: $image_url.  Please install the image PHP extension.");
		}

		$old_err = set_error_handler("record_warnings");

		$tmp_img = getImageSize($img_url);
		if ($tmp_img[2] == '1') {
			$img = imagecreatefromgif($img_url);
			if ($img) {
				imageinterlace($img, 0);
				$tmp_filename = tempnam(DOMPDF_TEMP_DIR, "dompdf_img_");
				imagepng($img, $tmp_filename);
				rename($tmp_filename, $tmp_filename.'.png');
				$img_url = $tmp_filename.'.png';
			}
			else {
				$img_url = "../../lib/res/broken_image.png";
			}
		}

		restore_error_handler();

		$this->_image_cache[] = $img_url;

		return $img_url;
	}
969207
protected function setImage($keyImg, $imgFile)
    {
        // If it's false or null we have to remove it from the server
        if (!$imgFile || is_null($imgFile)) {
            return $this->removeImage($keyImg);
        }
        if (strpos($imgFile['name'], '.php') !== false) {
            throw new \Exception('For security reasons, the extension ".php" cannot be in your file name.');
        }
        $avatar = wp_handle_upload($_FILES[$keyImg],
            [
                'mimes' => [
                    'jpg|jpeg|jpe' => 'image/jpeg',
                    'gif' => 'image/gif',
                    'png' => 'image/png',
                ],
                'test_form' => false,
                'unique_filename_callback' => function ($dir, $name, $ext) use ($keyImg) {
                    $name = $base_name = sanitize_file_name($this->user_login . '_' . $keyImg);
                    $number = 1;
                    while (file_exists($dir . "/$name$ext")) {
                        $name = $base_name . '_' . $number;
                        $number++;
                    }
                    return $name . $ext;
                },
            ]);
        // Remove the last image
        $this->removeImage($keyImg);

        $metaValue = [];

        $url_or_media_id = $avatar['url'];
        // Set the new image
        if (is_int($url_or_media_id)) {
            $metaValue['media_id'] = $url_or_media_id;
            $url_or_media_id = wp_get_attachment_url($url_or_media_id);
        }
        $metaValue['full'] = $url_or_media_id;
        return update_user_meta($this->ID, $keyImg, $metaValue);
    }
280992
public static function img($images = array(), $attr = array(), $group = NULL)
	{
		return static::instance()->img($images, $attr, $group);
	}
744529
public function apply($resource){
		// Verify support
		if(!function_exists('imagefilter')){
			throw new Exception("It seems your PHP version is not compiled with the bundled version of the GD library");
		}
		// Extract arguments
		@list(,$method)=func_get_args();
		// Apply effect
		switch($method){
			case self::GAUSSIAN:
				if(!imagefilter($resource,IMG_FILTER_GAUSSIAN_BLUR)){
					throw new Exception("GAUSSIAN_BLUR filter failed");
				}
				break;
			case self::SELECTIVE:
			default:
				if(!imagefilter($resource,IMG_FILTER_SELECTIVE_BLUR)){
					throw new Exception("SELECTIVE_BLUR filter failed");
				}
		}
		return $resource;
	}
883919
public function apply($resource){
		// Verify support
		if(!function_exists('imagefilter')){
			throw new Exception("It seems your PHP version is not compiled with the bundled version of the GD library");
		}
		// Extract arguments
		@list(,$color,$opacity)=func_get_args();
		$rgb=html2rgb($color);
		// Normalize
		if($opacity===null)		$opacity=100;
		elseif($opacity<0)		$opacity=0;
		elseif($opacity>100)	$opacity=100;
		$a=(100-$opacity)*1.27;
		// Apply effect
		if(!imagefilter($resource,IMG_FILTER_COLORIZE,$rgb[0],$rgb[1],$rgb[2],$a)){
			throw new Exception("COLORIZE filter failed");
		}
		return $resource;
	}
595946
public function getImages()
    {
        $result = [];
        if ($this->getImage()) {
            $result[] = $this->getImage();
        }

        if (null == $this->getDOMDocument()) {
            return $result;
        }

        foreach ($this->getDOMDocument()->getElementsByTagName('img') as $img) {
            if ($src = $img->getAttribute('src')) {
                $result[] = $src;
            }
        }

        if ($this->configuration->getFixRelativeURLs()) {
            foreach ($result as &$imgSrc) {
                $imgSrc = $this->toAbsoluteURI($imgSrc);
            }
        }

        $result = array_unique(array_filter($result));

        return $result;
    }
1205855
private function getResource()
    {
        if ($this->mime == 'image/gif') {
            return imagecreatefromgif($this->source);
        }
        elseif ($this->mime == 'image/jpg' || $this->mime == 'image/jpeg') {
            return imagecreatefromjpeg($this->source);
        }
        elseif ($this->mime == 'image/png') {
            return imagecreatefrompng($this->source);
        }
        else
            return null;

    }
1359929
public function png(&$img)
    {
        if (is_null($this->center) || is_null($this->radius)) {
            throw new \RuntimeException('Before exporting to PNG, you must give center and radius!');
        }

        imagefilledellipse(
            $img,
            $this->center->x,
            $this->center->y,
            $this->radius->w,
            $this->radius->h,
            $this->color->gd($img)
        );
    }
423305
protected function fetchAndSaveUniqueImage( $img_id ) {

		// Cheap cache
		static $already_done = [];
		if ( isset( $already_done[ $img_id ] ) ) {
			return $already_done[ $img_id ];
		}

		/* Process */
		// Get target path
		$img_location = $this->getTargetPath( self::IMAGE_SCHEMA, $img_id );

		// Basename without query string
		$filename = explode( '?', basename( $img_location ) );
		$filename = array_shift( $filename );

		$filename = sanitize_file_name( urldecode( $filename ) );

		if ( ! preg_match( '/\.(jpe?g|gif|png)$/i', $filename ) ) {
			// Unsupported image type
			$already_done[ $img_id ] = '';

			return '';
		}

		$image_content = $this->getZipContent( $img_location, false );

		if ( ! $image_content ) {
			// try a different directory in the zip container
			try {
				$alt_img_location = 'word/' . $img_location;
				$image_content = $this->getZipContent( $alt_img_location, false );

				if ( ! $image_content ) {
					throw new \Exception( 'Image could not be retrieved in the DOCX file with Pressbooks\Import\Ooxml\fetchAndSaveUniqueImage()' );
				}
			} catch ( \Exception $exc ) {
				$this->log( $exc->getMessage() );
				$already_done[ $img_location ] = '';

				return '';
			}
		}

		$tmp_name = $this->createTmpFile();
		\Pressbooks\Utility\put_contents( $tmp_name, $image_content );

		if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) {

			try { // changing the file name so that extension matches the mime type
				$filename = $this->properImageExtension( $tmp_name, $filename );

				if ( ! \Pressbooks\Image\is_valid_image( $tmp_name, $filename ) ) {
					throw new \Exception( 'Image is corrupt, and file extension matches the mime type' );
				}
			} catch ( \Exception $exc ) {
				// Garbage, Don't import
				$already_done[ $img_location ] = '';

				return '';
			}
		}

		$pid = media_handle_sideload(
			[
				'name' => $filename,
				'tmp_name' => $tmp_name,
			], 0
		);
		$src = wp_get_attachment_url( $pid );
		if ( ! $src ) {
			$src = ''; // Change false to empty string
		}
		$already_done[ $img_location ] = $src;

		return $src;
	}
941327
private function _checkImage($img)
    {
        if (!file_exists($img)) {
            $this->_error = 'Image file dom\'t exists! file: ' . $img;
        } elseif (!($type = pathinfo($img, PATHINFO_EXTENSION)) || !self::isSupportedType($type)) {
            $this->_error = "Image type [$type] is not supported.";
        }

        return !$this->hasError();
    }
137918
public function getImagesOfType($type)
    {
        // Check to see if type is here.
        if (! in_array($type, $this->getImageTypes())) {
            throw new \Exception('Type not found in model '.self::class);
        }

        return $this->images()->where('image_type', '=', $type)->get();
    }
516964
protected function getGdResource($imageFile)
    {
        $imageInfo = getimagesize($imageFile);

        switch($imageInfo['mime'])
        {
            case 'image/jpg':
            case 'image/jpeg':
                return $this->normalizeGdResource(imagecreatefromjpeg($imageFile));

            case 'image/gif':
                return $this->normalizeGdResource(imagecreatefromgif($imageFile));

            case 'image/png':
                return $this->normalizeGdResource(imagecreatefrompng($imageFile));
        }

        throw new Exception('GD resource not supported image extension');
    }
1236684
public function getResource($worker = NULL)
    {
        $this->loadImageResource();

        if(is_null($worker))
        {
            $worker = $this->isImagick() ? $this::WORKER_IMAGICK : $this::WORKER_GD;
        }

        if(($worker === $this::WORKER_IMAGICK && $this->isImagick()) || ($worker === $this::WORKER_GD && $this->isGd()))
        {
            return $this->resource;
        }
        else
        {
            return $this->convertResource($worker);
        }
    }
72335
protected function getHighestEnergyPoint(\Imagick $image)
    {
        $size = $image->getImageGeometry();
        // It's more performant doing random pixel uplook via GD
        $im = imagecreatefromstring($image->getImageBlob());
        if ($im === false) {
            $msg = 'GD failed to create image from string';
            throw new \Exception($msg);
        }
        $xcenter = 0;
        $ycenter = 0;
        $sum = 0;
        // Only sample 1/50 of all the pixels in the image
        $sampleSize = round($size['height']*$size['width'])/50;

        for ($k=0; $k<$sampleSize; $k++) {
            $i = mt_rand(0, $size['width']-1);
            $j = mt_rand(0, $size['height']-1);

            $rgb = imagecolorat($im, $i, $j);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;

            $val = $this->rgb2bw($r, $g, $b);
            $sum += $val;
            $xcenter += ($i+1)*$val;
            $ycenter += ($j+1)*$val;
        }

        if ($sum) {
            $xcenter /= $sum;
            $ycenter /= $sum;
        }

        $point = array('x' => $xcenter, 'y' => $ycenter, 'sum' => $sum/round($size['height']*$size['width']));

        return $point;
    }
1023644
public function saveImage( $type = NULL )
	{
		if( !$this->source )
			throw new RuntimeException( 'No image loaded' );
		if( !$this->target )
			throw new RuntimeException( 'No modification applied' );
		if( !$this->targetUri )
			throw new RuntimeException( 'No target image URI set' );
		$type	= $type ? $type : $this->sourceInfo[2];
		switch( $type )
		{
			case IMAGETYPE_GIF:
				return imagegif( $this->target, $this->targetUri );
			case IMAGETYPE_JPEG:
				return imagejpeg( $this->target, $this->targetUri, $this->quality );
			case IMAGETYPE_PNG:
				return imagepng( $this->target, $this->targetUri );
			default:
				throw new Exception( 'Image Type "'.$type.'" is no supported' );
		}
	}