{@inheritDoc}
@see \ImageStack\ImageOptimizer\AbstractExternalImageOptimizer::execExternalOptimizer()
541821
protected function execExternalOptimizer($if, &$binaryContent)
	{
	    $cmd = [
	        $this->getOption('jpegtran', 'jpegtran'),
	        $this->getOption('jpegtran_options', '-copy none -optimize'),
	        $if,
	    ];
	    $ret = null;
	    ob_start();
	    passthru(implode(' ', $cmd), $ret);
	    $binaryContent = ob_get_clean();
    	if ($ret !== 0) {
			throw new ImageOptimizerException(sprintf('Exec error jpegtran (%d)', $ret), ImageOptimizerException::EXEC_ERROR);
		}
	    return 'image/jpeg';
	}
228077
private function imageTypeToMimeType($imageExtension)
    {
        $this->validateImageExtension($imageExtension);
        $imageTypeEnum = $this->imageTypeMap[$imageExtension];

        return image_type_to_mime_type($imageTypeEnum);
    }
663163
public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        if (!isset($expression['parameters'])) {
            return false;
        }

        /*
         * Process the expected symbol to be returned
         */
        $call->processExpectedReturn($context);

        $symbolVariable = $call->getSymbolVariable();
        if ($symbolVariable) {
            if (!$symbolVariable->isVariable()) {
                throw new CompilerException('Returned values by functions can only be assigned to variant variables', $expression);
            }
        }

        $context->headersManager->add('kernel/variables');
        $resolvedParams = $call->getResolvedParamsAsExpr($expression['parameters'], $context, $expression);
        $resolvedParam = $resolvedParams[0];

        if (!$symbolVariable || !$symbolVariable->isVariable()) {
            /*
             * Complex expressions require a temporary variable
             */
            switch ($resolvedParam->getType()) {
                case 'array':
                    $type = 'array';
                    break;
                default:
                    $type = 'variable';
                    break;
            }

            $variable = $context->symbolTable->addTemp($type, $context);
            $variable->initVariant($context);

            $statement = new LetStatement([
                'type' => 'let',
                'assignments' => [
                    [
                        'assign-type' => $type,
                        'variable' => $variable->getName(),
                        'operator' => 'assign',
                        'expr' => [
                            'type' => $resolvedParam->getType(),
                            'value' => $resolvedParam->getCode(),
                            'file' => $expression['file'],
                            'line' => $expression['line'],
                            'char' => $expression['char'],
                        ],
                        'file' => $expression['file'],
                        'line' => $expression['line'],
                        'char' => $expression['char'],
                    ],
                ],
            ]);
            $statement->compile($context);
        } else {
            /**
             * This mark the variable as used.
             */
            $variable = $context->symbolTable->getVariableForRead($resolvedParam->getCode(), $context, $expression);
        }
        $variableSymbol = $context->backend->getVariableCodePointer($variable);

        /*
         * let a = var_export(val);
         */
        if ($symbolVariable) {
            if ('return_value' == $symbolVariable->getName()) {
                $symbolVariable = $context->symbolTable->getTempVariableForWrite('variable', $context);
            } else {
                $symbolVariable->initVariant($context);
            }
            $symbol = $context->backend->getVariableCode($symbolVariable);
            $context->codePrinter->output('zephir_var_export_ex('.$symbol.', '.$variableSymbol.' TSRMLS_CC);');

            return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression);
        }

        $context->codePrinter->output('zephir_var_export('.$variableSymbol.' TSRMLS_CC);');

        return new CompiledExpression('null', 'null', $expression);
    }
625037
public function setDefinition(ExecutableDefinitionInterface $definition): ContextBuilder
    {
        $this->definition = $definition;

        $type = null;
        if ($definition instanceof NodeAwareDefinitionInterface && $definition->getNode()) {
            $type = $definition->getNode();
        }

        if (!$type) {
            $type = $definition->getType();
        }

        if ($this->endpoint->hasType($type)
            && ($nodeDefinition = $this->endpoint->getType($type))
            && ($nodeDefinition instanceof ObjectDefinition || $nodeDefinition instanceof InterfaceDefinition)) {
            $this->node = $nodeDefinition;
        }

        return $this;
    }
199546
public function applyExprFromString($qb, $alias, $field, $exprValue, $namedParameter = null)
	{
		if (!$qb instanceof QueryBuilder && !$qb instanceof Builder) {
			throw new \InvalidArgumentException(sprintf('Argument 1 passed to "%s" must be an instance of "%s" or "%s", "%s" given.', __METHOD__, '\Doctrine\ORM\QueryBuilder', '\Doctrine\ODM\MongoDB\Query\Builder', gettype($qb)));
		}
		
		$value = $exprValue;
		$namedParameter = $namedParameter ?: ':'.$field;
		$dbDriver = $qb instanceof QueryBuilder ? 'orm' : 'mongodb';
		
		foreach ($this->mapConverters as $mapConverter) {
	        if (true === $this->supports($mapConverter, $dbDriver, $exprValue)) {
	            $converter = new $mapConverter['class']();
	            
	            if (!$converter instanceof QueryExprConverterInterface) {
	                throw new \RuntimeException(sprintf('Class "%s" must implemented interface "%s" for be used like query expression value converter.', $mapConverter['class'], '\Oka\PaginationBundle\Converter\QueryExprConverterInterface'));
	            }
	            
	            $expr = $converter->apply($dbDriver, $alias, $field, $exprValue, $namedParameter, $value);
	            break;
	        }
		}
		
		if ($qb instanceof QueryBuilder) {
			if (false === isset($expr)) {
				$expr = (new \Doctrine\ORM\Query\Expr())->eq($alias.'.'.$field, $namedParameter);
				$qb->setParameter($namedParameter, $exprValue);
			} else {
			    switch (true) {
			        case is_array($value):
			            foreach ($value as $key => $val) {
			                $qb->setParameter($key, $val);
			            }
			            break;
			        case null !== $value:
			            $qb->setParameter($namedParameter, $value);
			            break;
			    }
			}
			
			$qb->andWhere($expr);
		} else {
			$qb->addAnd(isset($expr) ? $expr : (new \Doctrine\MongoDB\Query\Expr())->field($field)->equals($value));
		}
	}
160932
public function apply( $image ) {

        $pixels = array();
        $finalPx = array();
        // Localize vars
        $width = $image->getWidth();
        $height = $image->getHeight();

        // Loop
        $pixelIterator = $image->getCore()->getPixelIterator();
        foreach ($pixelIterator as $y => $rows) { /* Loop through pixel rows */
            foreach ( $rows as $x => $px ) { /* Loop through the pixels in the row (columns) */

                // row 0
                if ($x > 0 and $y > 0) {
                    $matrix[0][0] = $this->getColor($px, $pixels, $x - 1, $y - 1);
                } else {
                    $matrix[0][0] = $this->getColor($px, $pixels, $x, $y);
                }

                if ($y > 0) {
                    $matrix[1][0] = $this->getColor($px, $pixels, $x, $y - 1);
                } else {
                    $matrix[1][0] = $this->getColor($px, $pixels, $x, $y);
                }

                if ($x + 1 < $width and $y > 0) {
                    $matrix[2][0] = $this->getColor($px, $pixels, $x + 1, $y - 1);
                } else {
                    $matrix[2][0] = $this->getColor($px, $pixels, $x, $y);
                }

                // row 1
                if ($x > 0) {
                    $matrix[0][1] = $this->getColor($px, $pixels, $x - 1, $y);
                } else {
                    $matrix[0][1] = $this->getColor($px, $pixels, $x, $y);
                }

                if ($x + 1 < $width) {
                    $matrix[2][1] = $this->getColor($px, $pixels, $x + 1, $y);
                } else {
                    $matrix[2][1] = $this->getColor($px, $pixels, $x, $y);
                }

                // row 1
                if ($x > 0 and $y + 1 < $height) {
                    $matrix[0][2] = $this->getColor($px, $pixels, $x - 1, $y + 1);
                } else {
                    $matrix[0][2] = $this->getColor($px, $pixels, $x, $y);
                }

                if ($y + 1 < $height) {
                    $matrix[1][2] = $this->getColor($px, $pixels, $x, $y + 1);
                } else {
                    $matrix[1][2] = $this->getColor($px, $pixels, $x, $y);
                }

                if ($x + 1 < $width and $y + 1 < $height) {
                    $matrix[2][2] = $this->getColor($px, $pixels, $x + 1, $y + 1);
                } else {
                    $matrix[2][2] = $this->getColor($px, $pixels, $x, $y);
                }

                $edge = $this->convolve($matrix);
                $edge = intval($edge / 2);
                if ($edge > 255) {
                    $edge = 255;
                }

                /**
                 * @var \ImagickPixel $px Current pixel.
                 */
                $finalPx[] = $edge; // R
                $finalPx[] = $edge; // G
                $finalPx[] = $edge; // B

            }
            $pixelIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
        }

        $new = new \Imagick();
        $new->newImage($width, $height, new \ImagickPixel('black'));
        /* Import the pixels into image.
        width * height * strlen("RGB") must match count($pixels) */
        $new->importImagePixels(0, 0, $width, $height, "RGB", \Imagick::PIXEL_CHAR, $finalPx);

        $type = $image->getType();
        $file = $image->getImageFile();

        return new Image( $new, $file, $width, $height, $type ); // Create new image with updated core

    }
298249
public function execute($image)
    {
        $size = $this->argument(0)->type('digit')->value(10);

        return imagefilter($image->getCore(), IMG_FILTER_PIXELATE, $size, true);
    }
1176751
public function setExif(string $exif) {
        if($this->setModified('exif', $exif)->isModified()) {
            $this->exif = $exif;
        }

        return $this;
    }
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;
	}
1178847
public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        if (!isset($expression['parameters']) || \count($expression['parameters']) < 2) {
            throw new CompilerException(
                sprintf(
                    'preg_match() expects at least 2 parameters, %d given',
                    isset($expression['parameters']) ? \count($expression['parameters']) : 0
                ),
                $expression
            );
        }

        if (\count($expression['parameters']) > 5) {
            throw new CompilerException(
                sprintf(
                    'preg_match() expects at most 5 parameters, %d given',
                    \count($expression['parameters'])
                ),
                $expression
            );
        }

        $matches = $this->createMatches($expression, $context);
        list($flags, $offset) = $this->processOptionals($expression, $call, $context);

        /*
         * Process the expected symbol to be returned
         */
        $call->processExpectedReturn($context);

        $symbolVariable = $call->getSymbolVariable(true, $context);
        if (!$symbolVariable->isVariable()) {
            throw new CompilerException(
                'Returned values by functions can only be assigned to variant variables',
                $expression
            );
        }

        // zephir_preg_match
        $context->headersManager->add('kernel/string');

        try {
            $resolvedParams = $call->getReadOnlyResolvedParams($expression['parameters'], $context, $expression);

            if ($call->mustInitSymbolVariable()) {
                $symbolVariable->initVariant($context);
            }

            $symbol = $context->backend->getVariableCode($symbolVariable);
            $matchesSymbol = $context->backend->getVariableCode($matches);

            $context->codePrinter->output(
                sprintf(
                    'zephir_preg_match(%s, %s, %s, %s, %d, %s, %s TSRMLS_CC);',
                    $symbol,
                    $resolvedParams[0],
                    $resolvedParams[1],
                    $matchesSymbol,
                    static::GLOBAL_MATCH,
                    $flags,
                    $offset
                )
            );

            return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression);
        } catch (Exception $e) {
            throw new CompilerException($e->getMessage(), $expression, $e->getCode(), $e);
        }
    }
698242
public function apply($resource){
		// Extract arguments
		@list(,$w_ratio,$h_ratio,$position)=func_get_args();
		$w_ratio=(float)$w_ratio;
		$h_ratio=(float)$h_ratio;
		if($w_ratio<=0 or $h_ratio<=0){
			throw new Exception("Ratio cannot be null or negative");
		}
		// Get resolution
		$w_src=imagesx($resource);
		$h_src=imagesy($resource);
		if($w_src===false or $h_src===false){
			throw new Exception("An error was encountered while getting image resolution");
		}
		// Compute basic chop dimensions
		$w_tmp=round(($h_src/$h_ratio)*$w_ratio);
		$h_tmp=round(($w_src/$w_ratio)*$h_ratio);
		if($w_tmp>$h_tmp){
			$width=$w_src;
			$height=$h_tmp;
		}
		else{
			$width=$w_tmp;
			$height=$h_src;
		}
		// Compute position
		switch($position){
			case self::LEFT:
				$x=0;
				if($w_ratio<$h_ratio)		$y=0;
				elseif($w_ratio>$h_ratio)	$y=round(($h_src-$height)/2);
				else						$y=round(($h_src-$height)/2);
				break;
			case self::RIGHT:
				$x=$w_src-$width;
				if($w_ratio<$h_ratio)		$y=0;
				elseif($w_ratio>$h_ratio)	$y=round(($h_src-$height)/2);
				else						$y=round(($h_src-$height)/2);
				break;
			case self::TOP:
				if($w_ratio<$h_ratio)		$x=round(($w_src-$width)/2);
				elseif($w_ratio>$h_ratio)	$x=0;
				else						$x=round(($w_src-$width)/2);
				$y=0;
				break;
			case self::BOTTOM:
				if($w_ratio<$h_ratio)		$x=round(($w_src-$width)/2);
				elseif($w_ratio>$h_ratio)	$x=0;
				else						$x=round(($w_src-$width)/2);
				$y=$h_src-$height;
				break;
			case self::CENTERED:
			default:
				if($w_ratio<$h_ratio){
					$x=round(($w_src-$width)/2);
					$y=0;
				}
				elseif($w_ratio>$h_ratio){
					$x=0;
					$y=round(($h_src-$height)/2);
				}
				else{
					$x=round(($w_src-$width)/2);
					$y=round(($h_src-$height)/2);
				}
		}
		// Chop image
		return parent::apply($resource,$x,$y,$width,$height);
	}
612598
public function optimize($exprRaw, CompilationContext $compilationContext)
    {
        $conditions = $this->optimizeNot($exprRaw, $compilationContext);

        if (false !== $conditions) {
            return $conditions;
        }

        /*
         * Discard first level parentheses
         */
        if ('list' == $exprRaw['type']) {
            $expr = new Expression($exprRaw['left']);
        } else {
            $expr = new Expression($exprRaw);
        }

        $expr->setReadOnly(true);
        $expr->setEvalMode(true);
        $compiledExpression = $expr->compile($compilationContext);

        /*
         * Possible corrupted expression?
         */
        if (!\is_object($compiledExpression)) {
            throw new CompilerException('Corrupted expression: '.$exprRaw['type'], $exprRaw);
        }

        /*
         * Generate the condition according to the value returned by the evaluated expression
         */
        switch ($compiledExpression->getType()) {
            case 'null':
                $this->unreachable = true;

                return '0';

            case 'int':
            case 'uint':
            case 'long':
            case 'ulong':
            case 'double':
                $code = $compiledExpression->getCode();
                if (is_numeric($code)) {
                    if ('1' == $code) {
                        $this->unreachableElse = true;
                    } else {
                        $this->unreachable = true;
                    }
                }

                return $code;

            case 'char':
            case 'uchar':
                return $compiledExpression->getCode();

            case 'bool':
                $code = $compiledExpression->getBooleanCode();
                if ('1' == $code) {
                    $this->unreachableElse = true;
                } else {
                    if ('0' == $code) {
                        $this->unreachable = true;
                    }
                }

                return $code;

            case 'variable':
                $variableRight = $compilationContext->symbolTable->getVariableForRead($compiledExpression->getCode(), $compilationContext, $exprRaw);
                $possibleValue = $variableRight->getPossibleValue();
                if (\is_object($possibleValue)) {
                    $possibleValueBranch = $variableRight->getPossibleValueBranch();
                    if ($possibleValueBranch instanceof Branch) {
                        /*
                         * Check if the possible value was assigned in the root branch
                         */
                        if (Branch::TYPE_ROOT == $possibleValueBranch->getType()) {
                            if ($possibleValue instanceof LiteralCompiledExpression) {
                                switch ($possibleValue->getType()) {
                                    case 'null':
                                        $this->unreachable = true;
                                        break;

                                    case 'bool':
                                        if ('0' == $possibleValue->getBooleanCode()) {
                                            $this->unreachable = true;
                                        } else {
                                            $this->unreachableElse = true;
                                        }
                                        break;

                                    case 'int':
                                        if (!(int) ($possibleValue->getCode())) {
                                            $this->unreachable = true;
                                        } else {
                                            $this->unreachableElse = true;
                                        }
                                        break;

                                    case 'double':
                                        if (!(float) ($possibleValue->getCode())) {
                                            $this->unreachable = true;
                                        } else {
                                            $this->unreachableElse = true;
                                        }
                                        break;

                                    default:
                                        //echo $possibleValue->getType();
                                }
                            }
                        }
                    }
                }

                $this->usedVariables[] = $variableRight->getName();

                /*
                 * Evaluate the variable
                 */
                switch ($variableRight->getType()) {
                    case 'int':
                    case 'uint':
                    case 'char':
                    case 'uchar':
                    case 'long':
                    case 'ulong':
                        return $variableRight->getName();

                    case 'string':
                        $variableRightCode = $compilationContext->backend->getVariableCode($variableRight);

                        return '!('.$compilationContext->backend->ifVariableValueUndefined($variableRight, $compilationContext, true, false).') && Z_STRLEN_P('.$variableRightCode.')';

                    case 'bool':
                        return $variableRight->getName();

                    case 'double':
                        return $variableRight->getName();

                    case 'variable':
                        $compilationContext->headersManager->add('kernel/operators');
                        $variableRightCode = $compilationContext->backend->getVariableCode($variableRight);

                        return 'zephir_is_true('.$variableRightCode.')';

                    default:
                        throw new CompilerException("Variable can't be evaluated ".$variableRight->getType(), $exprRaw);
                }
                break;

            default:
                throw new CompilerException('Expression '.$compiledExpression->getType()." can't be evaluated", $exprRaw);
        }
    }
983781
public function execute($image)
    {
        $amount = $this->argument(0)->between(0, 100)->value(10);

        // build matrix
        $min = $amount >= 10 ? $amount * -0.01 : 0;
        $max = $amount * -0.025;
        $abs = ((4 * $min + 4 * $max) * -1) + 1;
        $div = 1;

        $matrix = [
            [$min, $max, $min],
            [$max, $abs, $max],
            [$min, $max, $min]
        ];

        // apply the matrix
        return imageconvolution($image->getCore(), $matrix, $div, 0);
    }
948920
final function apply($settings = null, $throwException = false)
    {
        if ($settings !== null)
            $this->import($settings);

        # initialize specific environment
        $this->initApply();

        # do apply by current options value
        foreach($this as $prop => $value) {
            $method = 'do'.StdString::of($prop)->camelCase();
            if (! method_exists($this, $method) && $throwException)
                throw new \Exception(sprintf(
                    'Unknown instruction (%s).'
                    , $method
                ));
                
            
            $this->{$method}($value);
        }
    }
121251
public function optimizeImage(ImageInterface $image) {
	    if (!in_array($image->getMimeType(), $this->getSupportedMimeTypes())) {
			throw new ImageOptimizerException(sprintf('Unsupported MIME type : %s', $image->getMimeType()), ImageOptimizerException::UNSUPPORTED_MIME_TYPE);
	    }
	    $if = $this->getTempnam("if", $this->getInputFileExtension());
		if (!file_put_contents($if, $image->getBinaryContent())) {
			throw new ImageOptimizerException(sprintf('Cannot write tmpfile : %s', $if), ImageOptimizerException::CANNOT_WRITE_TMPFILE);
		}
		$binaryContent = null;
		$mimeType = $this->execExternalOptimizer($if, $binaryContent);
		unlink($if);
		$image->setBinaryContent($binaryContent, $mimeType);
	}
886644
public function execute($image)
    {
        $red = $this->argument(0)->between(-100, 100)->required()->value();
        $green = $this->argument(1)->between(-100, 100)->required()->value();
        $blue = $this->argument(2)->between(-100, 100)->required()->value();

        // normalize colorize levels
        $red = round($red * 2.55);
        $green = round($green * 2.55);
        $blue = round($blue * 2.55);

        // apply filter
        return imagefilter($image->getCore(), IMG_FILTER_COLORIZE, $red, $green, $blue);
    }
1030537
public static function fromResource($resource) {
        $newImage = new self();
        try {
            $newImage->setResource($resource);
        } catch(\Exception $e) {
            throw new ImageException($e->getMessage(), ImageException::UnsupportedFormatException, $e);
        }
        return $newImage;
    }