@param BoxInterface $imageSize
@param BoxInterface $watermarkSize

@return Point
@throws \Imagine\Exception\InvalidArgumentException
970682
private function getPositionPoint(BoxInterface $imageSize, BoxInterface $watermarkSize): Point
    {
        return new Point(
            (int) (($imageSize->getWidth() - $watermarkSize->getWidth()) / 2),
            (int) (($imageSize->getHeight() - $watermarkSize->getHeight()) / 2)
        );
    }
810693
function cloneImage( $imageObject, $width, $height, $useTruecolor = null )
    {
        if ( $this->ImageObject !== null and
             $this->ImageObjectRef !== null )
        {
            $this->destroy();
        }
        $this->ImageObject = eZImageInterface::createImage( $width, $height, $useTruecolor );
        $this->IsTrueColor = $useTruecolor;
        $this->ImageObjectRef = eZImageInterface::registerImage( $this->ImageObject );
        ImageCopy( $this->ImageObject, $imageObject, 0, 0, 0, 0, $width, $height );
    }
1334730
public static function fromKiloBytesString($filesize)
    {
        if (!is_string($filesize)) {
            throw new InvalidArgumentException('Given filesize must be a string');
        }

        if (!preg_match('#^([0-9]*\.[0-9]+|[0-9]*)\s?KB$#', $filesize, $matches)) {
            throw new RuntimeException('Given filesize is not in a valid format. Need: "<float> KB"');
        }

        $kilobytes = $matches[1];

        if (($filtered = filter_var($kilobytes, FILTER_VALIDATE_INT)) !== false) {
            $kilobytes = $filtered;
        } else {
            $kilobytes = (float) $kilobytes;
        }

        return self::fromKiloBytes($kilobytes);
    }
1202299
private function applyLetterbox(&$imageInstance, $transform)
    {
        if (isset($transform['width'], $transform['height'])) { // if both isn't set, there's no need for a letterbox
            /** @var ConfigModel $settings */
            $config = ImagerService::getConfig();

            $letterboxDef = $config->getSetting('letterbox', $transform);

            try {
                $size = new Box($transform['width'], $transform['height']);

                $position = new Point(
                    (int)floor(((int)$transform['width'] - $imageInstance->getSize()->getWidth()) / 2),
                    (int)floor(((int)$transform['height'] - $imageInstance->getSize()->getHeight()) / 2)
                );
            } catch (InvalidArgumentException $e) {
                Craft::error($e->getMessage(), __METHOD__);
                throw new ImagerException($e->getMessage(), $e->getCode(), $e);
            }

            $palette = new RGB();
            $color = $palette->color(
                $letterboxDef['color'] ?? '#000',
                isset($letterboxDef['opacity']) ? (int)($letterboxDef['opacity'] * 100) : 0
            );
            
            if ($this->imagineInstance !== null) {
                $backgroundImage = $this->imagineInstance->create($size, $color);
                $backgroundImage->paste($imageInstance, $position);
                $imageInstance = $backgroundImage;
            }
        }
    }
897628
public function setSize($size)
    {
        if (!is_numeric($size) || $size < 1) {
            throw new \InvalidArgumentException(
                "An invalid identicon size was specified. ".
                "A numeric value >= 1 was expected. Specified value: $size.");
        }
        
        $this->size = (int)$size;
    }
353195
public static function getCacheLocation($imageFile, $width) {
    // get file name and cache directory
    $baseName = FileUtil::basename($imageFile);
    $directory = self::getCacheDir($imageFile);
    return self::makeRelative($directory.(strlen($width) > 0 ? $width.'-' : '').$baseName);
  }
599266
public function doFilter($originalImage, $arguments, $imageOptions)
    {
        // Need at least a height or a width
        if (empty($arguments['height']) && empty($arguments['width'])) {
            throw new ErrorException('You must set at least the height (h) or the width (w)');
        }
        switch (strtolower($imageOptions['imageProcessor'])) {
            case 'gd':
                $Imagine = new \Imagine\Gd\Imagine();
                break;
            case 'imagick':
                $Imagine = new \Imagine\Imagick\Imagine();
                break;
            case 'gmagick':
                $Imagine = new \Imagine\Gmagick\Imagine();
                break;
            default:
                throw new ErrorException('Unsupported imageProcessor config value: ' . $imageOptions['imageProcessor']);
        }
        $image = $Imagine->open($originalImage);

        $size = $image->getSize();
        $originalWidth = $size->getWidth();
        $originalHeight = $size->getHeight();
        $width = $originalWidth;
        $height = $originalHeight;

        if (! empty($arguments['height'])) {
            if ($originalHeight > $arguments['height'] || $arguments['stretch']) {
                $height = $arguments['height'];
            }
        }
        if (! empty($arguments['width'])) {
            if ($originalWidth > $arguments['width'] || $arguments['stretch']) {
                $width = $arguments['width'];
            }
        }

        /**
         * Prevent from someone from creating huge images
         */
        if ($width > $imageOptions['maxAllowedResizeWidth']) {
            $width = $imageOptions['maxAllowedResizeWidth'];
        }

        if ($height > $imageOptions['maxAllowedResizeHeight']) {
            $height = $imageOptions['maxAllowedResizeHeight'];
        }

        $mode = $arguments['exact'] ?
            ImageInterface::THUMBNAIL_OUTBOUND :
            ImageInterface::THUMBNAIL_INSET;

        $newSize = new Box($width, $height);

        $newImage = $image->thumbnail($newSize, $mode);
        if ($arguments['fill']) {
            $adjustedSize = $newImage->getSize();
            $canvasWidth = isset($arguments['width']) ? $arguments['width'] : $adjustedSize->getWidth();
            $canvasHeight = isset($arguments['height']) ? $arguments['height'] : $adjustedSize->getHeight();
            /**
             * Prevent from someone from creating huge images
             */
            if ($canvasWidth > $imageOptions['maxAllowedResizeWidth']) {
                $canvasWidth = $imageOptions['maxAllowedResizeWidth'];
            }

            if ($canvasHeight > $imageOptions['maxAllowedResizeHeight']) {
                $canvasHeight = $imageOptions['maxAllowedResizeHeight'];
            }

            $palette = new RGB();
            $canvas = $Imagine->create(
                new Box($canvasWidth, $canvasHeight),
                $palette->color($arguments['fillColour'])
            );

            // Put image in the middle of the canvas
            $newImage = $canvas->paste($newImage, new Point(
                (int) (($canvasWidth - $adjustedSize->getWidth()) / 2),
                (int) (($canvasHeight - $adjustedSize->getHeight()) / 2)
            ));
        }

        $newImage->save($originalImage, array('jpeg_quality' => $arguments['quality']));
    }
1073840
private function calculateCrop(array $parameters, array $imageSize) {
        $focalX = $parameters['poi'][0];
        $focalY  = $parameters['poi'][1];

        $sourceWidth = $imageSize['width'];
        $sourceHeight = $imageSize['height'];
        $sourceRatio  = $sourceWidth / $sourceHeight;

        $targetWidth = $parameters['width'];
        $targetHeight = $parameters['height'];
        $targetRatio  = $targetWidth / $targetHeight;

        $growFactor = $this->getGrowFactor($parameters['closeness']);
        $sourcePortionThreshold = $this->getSourcePercentageThreshold($parameters['closeness']);

        if ($sourceRatio >= $targetRatio) {
            // Image is wider than needed, crop from the sides
            $cropWidth = (int) ceil(
                $targetRatio * max(
                    min($sourceHeight, $targetHeight * $growFactor),
                    $sourceHeight * $sourcePortionThreshold
                )
            );
            $cropHeight = (int) floor($cropWidth / $targetRatio);
        } else {
            // Image is taller than needed, crop from the top/bottom
            $cropHeight = (int) ceil(
                max(
                    min($sourceWidth, $targetWidth * $growFactor),
                    $sourceWidth * $sourcePortionThreshold
                ) / $targetRatio
            );
            $cropWidth = (int) floor($cropHeight * $targetRatio);
        }

        $cropTop = (int) ($focalY - floor($cropHeight / 2));
        $cropLeft = (int) ($focalX - floor($cropWidth / 2));

        // Make sure that we're not cropping outside the image on the x axis
        if ($cropLeft < 0) {
            $cropLeft = 0;
        } else if ($cropLeft + $cropWidth > $sourceWidth) {
            $cropLeft = $sourceWidth - $cropWidth;
        }

        // Make sure that we're not cropping outside the image on the y axis
        if ($cropTop < 0) {
            $cropTop = 0;
        } else if ($cropTop + $cropHeight > $sourceHeight) {
            $cropTop = $sourceHeight - $cropHeight;
        }

        return [
            'width' => $cropWidth,
            'height' => $cropHeight,
            'x' => $cropLeft,
            'y' => $cropTop,
        ];
    }
969356
private function setImageSize($image, $size, $needExactSize = false)
    {
        if (empty($size)) {
            return $image;
        }

        if ($needExactSize || $image->getImageWidth() > $size[0]) {
            if ($size[0] == 0 || $size[1] == 0) {
                $image->scaleImage($size[0], $size[1]);
            } else {
                $image->cropThumbnailImage($size[0], $size[1]);
            }
        }

        return $image;
    }
437213
public function watermark(ImageResource $watermark, $watermarkPos = 4, $watermarkMargin = 10) {
		switch($watermarkPos) {
			// center
			case 0:
				$watermarkdestX = $this->width/2 - $watermark->getWidth()/2;
				$watermarkdestY = $this->height/2 - $watermark->getHeight()/2;
				break;
				// top left
			case 1:
				$watermarkdestX = $watermarkMargin;
				$watermarkdestY = $watermarkMargin;
				break;
				// top right
			case 2:
				$watermarkdestX = $this->width - $watermark->getWidth() - $watermarkMargin;
				$watermarkdestY = $watermarkMargin;
				break;
				// bottom left
			case 3:
				$watermarkdestX = $watermarkMargin;
				$watermarkdestY = $this->height - $watermark->getHeight() - $watermarkMargin;
				break;
				// bottom right
			case 4:
			default:
				$watermarkdestX = $this->width - $watermark->getWidth() - $watermarkMargin;
				$watermarkdestY = $this->height - $watermark->getHeight() - $watermarkMargin;
				break;
		}

		// set transparency true
		imagealphablending($this->resource, true);
		$watermarkRes = $watermark->getResource();
		imagealphablending($watermarkRes, true);
		imagecopy($this->resource, $watermarkRes, $watermarkdestX, $watermarkdestY, 0, 0, $watermark->getWidth(), $watermark->getHeight());
	}
527780
public function apply(TranscodeInterface $media, FormatInterface $format)
	{
		if ( ! $format instanceof FrameFormatInterface)
		{
			throw new \InvalidArgumentException('The filter resize can be used only with the format of the frame.');
		}
		
		$format = $media->getFormat();
		$dimension = new Dimension($format->getWidth(), $format->getHeight());
		
		if ($this->width && ! $this->height) // Resize to width
		{
			$this->height = $this->width / $dimension->getRatio();
		}
		
		if ( ! $this->width && $this->height) // Resize to height
		{
			$this->width = $this->height * $dimension->getRatio();
		}
		
		// If the dimensions are the same, there's no need to resize.
		if($dimension->getWidth() === $this->width && $dimension->getHeight() === $this->height)
		{
			return [];
		}
		
		return [
			'filter:v' => [
				'scale' => http_build_query([
					'w' => $this->width,
					'h' => $this->height
				], null, ':')
			]
		];
	}
1073716
protected function handleImageManipulation(ImageInterface $image, array $data): ImageInterface
    {
        $width = $data['width'];
        $height = $data['height'];

        if (isset($data['dimension'])) {
            $width = $height = $data['dimension'];
        }

        return $image->resize(new Box($width, $height), $data['filter']);
    }
338133
protected function do_watermark(\stdClass $src, $watermarkFile) {

		$stamp			= imagecreatefrompng($watermarkFile);
		$stampWidth		= imagesx($stamp);
		$stampHeight	= imagesy($stamp);

		$dst = new \stdClass();
		$dst->resource	= imagecreatetruecolor($src->width, $src->height);
		$dst->width		= $src->width;
		$dst->height	= $src->height;

		// stamp is centered onto source image, opacity 50%
		imagecopy($dst->resource, $src->resource, 0, 0, 0, 0, $src->width, $src->height);

		$this->imagecopymerge_alpha(
			$dst->resource,
			$stamp,
			($src->width - $stampWidth) / 2,
			($src->height - $stampHeight) / 2,
			0, 0,
			$stampWidth,
			$stampHeight,
			100
		);

		return $dst;
	}
1078680
static function imageCopy( $imageObject, $destinationGeometry, $sourceGeometry,
                               $sourceMimeData, $destinationMimeData )
    {
        $destinationWidth = $destinationGeometry['width'];
        $destinationHeight = $destinationGeometry['height'];

        $temporaryImageObject = eZImageGDHandler::imageCreate( $destinationWidth, $destinationHeight, eZImageGDHandler::isImageTrueColor( $imageObject, $sourceMimeData ) );
        ImageCopy( $temporaryImageObject, $imageObject,
                   $destinationGeometry['x'], $destinationGeometry['y'],
                   $sourceGeometry['x'], $sourceGeometry['y'], $sourceGeometry['width'], $sourceGeometry['height'] );
        return $temporaryImageObject;
    }
637262
protected function addWatermarkFilterIfExists(&$set, $width, $height)
    {
        if( isset($set['watermark']) )
        {
            if( ! empty($set['watermark'][1])) 
            {
                $set['filters'][] = ['target', [$set['watermark'][1]]];
            }

            if( ! empty($set['watermark'][2])) 
            {
                $set['filters'][] = ['margin', [$set['watermark'][2]]];
            }

            $set['filters'][] = ['mix', [$set['watermark'][0]]];
        }  
    }
231191
protected function slice($image, $originalSize, $targetSize, $axis)
    {
        $aSlice = null;
        $bSlice = null;

        // Just an arbitrary size of slice size
        $sliceSize = ceil(($originalSize - $targetSize) / 25);

        $aBottom = $originalSize;
        $aTop = 0;

        // while there still are uninvestigated slices of the image
        while ($aBottom - $aTop > $targetSize) {
            // Make sure that we don't try to slice outside the picture
            $sliceSize = min($aBottom - $aTop - $targetSize, $sliceSize);

            // Make a top slice image
            if (!$aSlice) {
                $aSlice = clone $image;
                if ($axis === 'h') {
                    $aSlice->cropImage($sliceSize, $originalSize, $aTop, 0);
                } else {
                    $aSlice->cropImage($originalSize, $sliceSize, 0, $aTop);
                }
            }

            // Make a bottom slice image
            if (!$bSlice) {
                $bSlice = clone $image;
                if ($axis === 'h') {
                    $bSlice->cropImage($sliceSize, $originalSize, $aBottom - $sliceSize, 0);
                } else {
                    $bSlice->cropImage($originalSize, $sliceSize, 0, $aBottom - $sliceSize);
                }
            }

            // calculate slices potential
            $aPosition = ($axis === 'h' ? 'left' : 'top');
            $bPosition = ($axis === 'h' ? 'right' : 'bottom');

            $aPot = $this->getPotential($aPosition, $aTop, $sliceSize);
            $bPot = $this->getPotential($bPosition, $aBottom, $sliceSize);

            $canCutA = ($aPot <= 0);
            $canCutB = ($bPot <= 0);

            // if no slices are "cutable", we force if a slice has a lot of potential
            if (!$canCutA && !$canCutB) {
                if ($aPot * self::POTENTIAL_RATIO < $bPot) {
                    $canCutA = true;
                } elseif ($aPot > $bPot * self::POTENTIAL_RATIO) {
                    $canCutB = true;
                }
            }

            // if we can only cut on one side
            if ($canCutA xor $canCutB) {
                if ($canCutA) {
                    $aTop += $sliceSize;
                    $aSlice = null;
                } else {
                    $aBottom -= $sliceSize;
                    $bSlice = null;
                }
            } elseif ($this->grayscaleEntropy($aSlice) < $this->grayscaleEntropy($bSlice)) {
                // bSlice has more entropy, so remove aSlice and bump aTop down
                $aTop += $sliceSize;
                $aSlice = null;
            } else {
                $aBottom -= $sliceSize;
                $bSlice = null;
            }
        }

        return $aTop;
    }
378269
public function thumbnailAction($storageId, $height, $width)
    {
        $fileManager = $this->get('beaast.core.manager.file');

        /**
         * @var File $file
         */
        $file = $fileManager->findOneBy(['storageId' => $storageId]);

        if (!$file || !in_array($file->getExtension(), ['jpg', 'png', 'gif'], true)) {
            throw $this->createNotFoundException();
        }

        $filePath = $fileManager->getFilePath($file);

        $cacheFileName = 'thumbnail_'.$height.'_'.$width.'_'.$storageId.'.'.$file->getExtension();

        $cacheFilePath = $this->getParameter('kernel.root_dir').'/../var/storage/cache/'.$cacheFileName;
        if (!file_exists($cacheFilePath) && file_exists($filePath)) {
            $imagick = new \Imagick($filePath);
            $imagick->thumbnailImage($width, $height, true);
            file_put_contents($cacheFilePath, $imagick->getImageBlob());
        }

        return $this->cacheAction($cacheFileName);
    }