Shortcut to run a "convert" command => creates a new image

@param string $format ImBundle format string
@param string $file Source file path

@return string
@codeCoverageIgnore
555582
public function convert($format, $file)
    {
        $file = ltrim($file, '/');
        $this->checkImage($file);

        return $this->wrapper->run("convert", $this->getWebDirectory() . '/' . $file, $this->convertFormat($format), $this->getCacheDirectory() . '/' . $this->pathify($format) . '/' . $file);
    }
266900
public function getScaledImage(
        File $file,
        $urlType = 'default',
        $width = null,
        $height = null,
        $filename = null,
        $quality = null
    ) {

        if ($width != null && $height != null) {
            return $this->getResizedImage($file, $urlType, $width, $height, false, $filename, $quality);
        }

        if ($this->mustBuildImage($file, $filename) || $filename == null) {
            $binary = $this->getBinary($file);

            if ($binary) {
                $imagine = new Imagine();
                $image   = $imagine->load($binary);

                $size  = $image->getSize();
                $ratio = $size->getWidth() / $size->getHeight();

                if ($width == null) {
                    $width = $height * $ratio;
                } else {
                    $height = $width / $ratio;
                }

                $filename = $this->determineFileName($file, $width, $height, 's', $filename);
                if ($this->mustBuildImage($file, $filename)) {
                    if ($this->keepOriginalImage($binary, $width, $height)) {
                        return $this->getOriginalImage($file, $urlType, $filename);
                    }

                    $image->resize(new Box($width, $height));

                    $quality = $this->determineQuality($quality);
                    $image->save($this->basePath . '/' . $filename, array('quality' => $quality));
                }

            } else {
                return false;
            }
        }

        $url = $this->baseUrl . '/' . $filename;

        $file->addUrl($urlType, $url);

        return $file;
    }
784608
protected function _process(File $file, array $options) {
        if (!$file->isImage()) {
            throw new DomainException(sprintf('%s is not a valid image', $file->basename()));
        }

        $sourcePath = $file->path();
        $mimeType = $file->type();

        // Create an image to work with
        switch ($mimeType) {
            case 'image/gif':
                $sourceImage = @imagecreatefromgif($sourcePath);
            break;
            case 'image/png':
                $sourceImage = @imagecreatefrompng($sourcePath);
            break;
            case 'image/jpg':
            case 'image/jpeg':
            case 'image/pjpeg':
                $sourceImage = @imagecreatefromjpeg($sourcePath);
            break;
            default:
                $sourceImage = false;
            break;
        }

        if (!$sourceImage) {
            throw new DomainException(sprintf('%s can not be transformed', $mimeType));
        }

        // Gather options
        $options = $options + array(
            'width' => null,
            'height' => null,
            'dest_x' => 0,
            'dest_y' => 0,
            'dest_w' => null,
            'dest_h' => null,
            'source_x' => 0,
            'source_y' => 0,
            'source_w' => $file->width(),
            'source_h' => $file->height(),
            'quality' => 100,
            'overwrite' => false,
            'target' => '',
            'preCallback' => '',
            'postCallback' => ''
        );

        $options = array_map(function($value) {
            if (is_numeric($value)) {
                $value = round($value);
            }

            return $value;
        }, $options);

        $width = $options['width'] ?: $options['dest_w'];
        $height = $options['height'] ?: $options['dest_h'];
        $targetImage = imagecreatetruecolor($width, $height);

        // If gif/png allow transparencies
        if ($mimeType === 'image/gif' || $mimeType === 'image/png') {
            imagealphablending($targetImage, false);
            imagesavealpha($targetImage, true);
            imagefill($targetImage, 0, 0, imagecolorallocatealpha($targetImage, 255, 255, 255, 127));
        }

        // Trigger a callback to prepare the image
        if (is_callable($options['preCallback'])) {
            $targetImage = call_user_func_array($options['preCallback'], array($targetImage, $options));
        }

        // Lets take our source and apply it to the temporary file and resize
        imagecopyresampled($targetImage, $sourceImage, $options['dest_x'], $options['dest_y'], $options['source_x'], $options['source_y'], $options['dest_w'], $options['dest_h'], $options['source_w'], $options['source_h']);

        // Trigger a callback to modify the image
        if (is_callable($options['postCallback'])) {
            $targetImage = call_user_func_array($options['postCallback'], array($targetImage, $options));
        }

        // Now write the transformed image to the server
        if ($options['overwrite']) {
            $options['target'] = $file->name();

        } else if (!$options['target']) {
            $class = explode('\\', get_class($this));
            $class = str_replace('transformer', '', strtolower(end($class)));

            $options['target'] = sprintf('%s-%s-%sx%s-%s', $file->name(), $class, $width, $height, uniqid());
        }

        $targetPath = sprintf('%s%s.%s', $file->dir(), $options['target'], $file->ext());

        switch ($mimeType) {
            case 'image/gif':
                imagegif($targetImage, $targetPath);
            break;
            case 'image/png':
                imagepng($targetImage, $targetPath);
            break;
            case 'image/jpg':
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($targetImage, $targetPath, $options['quality']);
            break;
        }

        // Clear memory
        imagedestroy($sourceImage);
        imagedestroy($targetImage);

        return new File($targetPath);
    }
39534
public static function createFromFile(PHPRtfLite $rtf, $file, $width = null, $height = null)
    {
        if (is_readable($file)) {
            $stream = fopen($file, 'rb');
            $pathInfo = pathinfo($file);
            $type = isset($pathInfo['extension']) ? strtolower($pathInfo['extension']) : 'jpeg';
            $image = self::create($rtf, $stream, $type, $width, $height);

            if ($type != self::TYPE_WMF) {
                list($width, $height, $imageType) = getimagesize($file);
                $imageType = image_type_to_extension($imageType, false);
                $image->setImageWidth($width);
                $image->setImageHeight($height);
                if ($type != $imageType) {
                    $image->setImageType($imageType);
                }
            }
            return $image;
        }

        return self::createMissingImage($rtf, $width, $height);
    }
1083976
public static function create($path, $format)
    {
        switch ($format) {
            case IMAGETYPE_JPEG:
                $result = imagecreatefromjpeg($path);
                break;
            case IMAGETYPE_PNG:
                $result = imagecreatefrompng($path);
                break;
            case IMAGETYPE_GIF:
                $result = imagecreatefromgif($path);
                break;
        }

        if (!$result) {
            throw new \Exception("Failing to create image (" . $path . ")");
        }

        return $result;
    }
332233
public static function loadFile($file, $format = null)
    {
        if (!isset($format)) {
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            $format = ArrayHelper::fetch(self::$FORMATS, $ext);
            if (!isset($format)) {
                throw new \InvalidArgumentException("Cannot infer format from file '{$file}'");
            }
        }
        if ($format == 'json') {
            return json_decode(file_get_contents($file), true);
        } elseif ($format == 'yaml') {
            return Yaml::parse(file_get_contents($file));
        } elseif ($format == 'php') {
            return require($file);
        } else {
            throw new \InvalidArgumentException("Invalid format '{$format}'");
        }
    }
721201
protected function makeImage($file = null, $quality = null)
  {
    $dir = dirname($file);
    if (!is_dir($dir)) {
      mkdir($dir, 0777, true);
    }

    switch ($this->getTypeByFile($file)) {
      case IMG_JPG:
        return imagejpeg($this->image, $file, $quality ? : static::QUALITY_JPG);
        break;
      case IMG_PNG:
        return imagepng($this->image, $file, $quality ? : static::QUALITY_PNG);
        break;
      case IMG_GIF:
        return imagegif($this->image, $file);
        break;
      default:
        Ex::ThrowError(Ex::BAD_TYPE);
    }
  }
1226138
public function object($image, int $format = 1, int $topk = 5)
    {
        $image = self::encode($image);

        return Request::exec(self::OBJECT, compact('image', 'format', 'topk'));
    }
857630
public function generate($file = null) {

		if(null !== $file && false === is_string($file)) {
            return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($file)), E_USER_ERROR);
        }

		if(null === $this -> image) {
			return trigger_error('Can not generate captcha image without valid background image. Set background image with setImage() method', E_USER_ERROR);
		}

		if(null === $this -> font) {
			return trigger_error('Can not generate captcha image without valid font. Set font with setFont() method', E_USER_ERROR);
		}

		//Generate and set text if not already set
		if(null === $this -> getText()) {
			$this -> setText($this -> generateText());
		}

		$text 	= $this -> getText();
		$image 	= $this -> image -> entity();
		$font 	= $this -> font -> entity();

		//Add image header
		if(null === $file) {
			Response :: addHeader('Content-type', $this -> image -> getMime());
		}
		else {
			
			$file = new File($file);

			if(false === in_array($file -> entity() -> getExtension(), ['png', 'jpg', 'jpeg'])) {
				return trigger_error(sprintf('Argument 1 passed to %s() must have the jpg, jpeg or png extension, "%s" given', __METHOD__, $file -> entity() -> getExtension()), E_USER_ERROR);
			}
		}

		//Create image
		switch(strtolower($image -> getExtension())) {
			
			case 'png' 	: $img = imagecreatefrompng($image -> getBasepath()); break;
			default 	: $img = imagecreatefromjpeg($image -> getBasepath());
		}

		//Generate output object
		$output = [];

		for($i = 0; $i < strlen($text); $i++) {

			$fontsize 	= rand($this -> fontsize['min'], $this -> fontsize['max']);
			$angle 		= rand($this -> angle['min'], $this -> angle['max']);
			$tb 		= imagettfbbox($fontsize, $angle, $font -> getBasepath(), $text[$i]);
			$color 		= imagecolorallocate($img, $this -> color['r'], $this -> color['g'], $this -> color['b']);
			$width 		= $image -> getWidth() / strlen($text);
			$width 		= $width < 2 ? 3 : $width;
			$tries 		= 0;

			if($tb[2] >= $width && $tries < 20) {

				$this -> fontsize['min']--;
				$i--;
				$tries++;

				continue;
			}

			$output[] 	= [

				'text' 		=> $text[$i], 
				'width' 	=> $tb[2], 
				'height' 	=> $tb[1],
				'angle'		=> $angle,
				'fontsize' 	=> $fontsize, 
				'color' 	=> $color
			];
		}

		foreach($output as $index => $char) {

			$x = $width * $index + rand(0, $width - $char['width']);
			$y = rand($char['fontsize'], $image -> getHeight() - $char['height']);
			
			imagettftext($img, $char['fontsize'], $char['angle'], $x, $y, $char['color'], $font -> getBasepath(), $char['text']);
		}
		
		$extension 	= $file !== null ? $file -> entity() -> getExtension() : $image -> getExtension();
		$file 		= $file !== null ? $file -> entity() -> getBasepath() : null;

		//Show image
		switch(strtolower($extension)) {
			
			case 'png' 	: imagepng($img, $file); break;
			default 	: imagejpeg($img, $file);
		}
	}
1334131
public function encode($image, $format, $quality)
    {
        return $this->encoder->process($image, $format, $quality);
    }
81812
public function save($filename = '', $quality = 100, $format = '')
    {
        if (empty($filename)) {
            $filename = $this->filename;
        }

        if (empty($format)) {
            $format = $this->format;
        }

        $arguments = array($this->image, $filename);

        if (in_array($format, array('jpg', 'jpeg'))) {
            $format = 'jpeg';
            imageinterlace($this->image, true);
            $arguments = array($this->image, $filename, round($quality));
        } else if ($format === 'png') {
            $arguments = array($this->image, $filename, round(9 * $quality / 100));
        }

        return $this->callFunction('image', $format, $arguments);
    }
438412
public function upload($file, $format = 'json')
	{
		// Is this "file" a URL?
		$url = filter_var($file, FILTER_VALIDATE_URL) !== false;

		$data = array(
			'key' => $this->key,
			'format' => $format
		);

		if ($url) {
			$data['url'] = $file;
		} else {
			$data['fileupload'] = $file;
		}

		if ($this->credentials) {
			$data['a_username'] = $this->credentials['username'];
			$data['a_password'] = $this->credentials['password'];
		} else if($this->cookie) {
			$data['cookie'] = $this->cookie;
		}

		return $this->post('https://post.imageshack.us/upload_api.php', $data);
	}
1163438
public static function fromString(string $format)
    {
        if (preg_match('/^(([^-]|--)+)-(([^-]|--)+)-(([^-]|--)+)\.(svg|png|gif|jpg)$/', $format, $match) === false && (7 != count($match))) {
            throw new InvalidArgumentException('The given format string is invalid: '.$format);
        }

        $subject = $match[1];
        $status = $match[3];
        $color = $match[5];
        $format = $match[7];

        return new self($subject, $status, $color, $format);
    }
1095866
public function setImage($file) {

		if(false === is_string($file)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($file)), E_USER_ERROR);
		}

		if(false === is_file($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() does not exists', $file, __METHOD__), E_USER_ERROR);
		}

		if(false === is_readable($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() is not readable', $file, __METHOD__), E_USER_ERROR);
		}

		$info = @getimagesize($file);

		if(false === is_array($info) || count($info) < 3) {
			return trigger_error(sprintf('File "%s" passed to %s() is not an image', $file, __METHOD__), E_USER_ERROR);
		}

		$this -> image 	 	= @imagecreatefromstring(file_get_contents($file));
		$this -> extension 	= pathinfo($file, PATHINFO_EXTENSION);

		return $this;
	}
1271821
public static function get($file)
    {
        $type = str_replace('image/', NULL, Singleton::class('ZN\Helpers\Mime')->type($file));

        return $type === 'jpg' ? 'jpeg' : $type;
    }
378017
protected function resizeImage(array $format, Imagick $image)
    {
        $maxWidth = array_key_exists('max_width', $format)? $format['max_width']: $this->maxWidth;
        $maxHeight = array_key_exists('max_height', $format)? $format['max_height']: $this->maxHeight;
        if ($maxWidth > $this->maxWidth) {
            $maxWidth = $this->maxWidth;
        }
        if ($maxHeight > $this->maxHeight) {
            $maxHeight = $this->maxHeight;
        }

        $image->setimagebackgroundcolor('#000000');
        $image->resizeImage($maxWidth, $maxHeight, Imagick::FILTER_LANCZOS, 1, true);

        return $image;
    }
720785
private function convertPdfToImage($resource)
    {
        $temporaryFilePath = $this->createTemporaryFile($resource);

        $command = $this->ghostScriptPath .
            ' -dNOPAUSE -sDEVICE=jpeg -dFirstPage=1 -dLastPage=1 -sOutputFile=' . $temporaryFilePath . ' ' .
            '-dJPEGQ=100 -r300x300 -q ' . $temporaryFilePath . ' -c quit 2> /dev/null';

        shell_exec($command);
        $output = file_get_contents($temporaryFilePath);
        unlink($temporaryFilePath);

        if (!$output) {
            throw new GhostScriptNotFoundException(
                'Ghostscript was not found at "' .
                $this->ghostScriptPath .
                '"'
            );
        }

        return $this->createTemporaryResource($output);
    }