protected function getTransformation(AbstractFileEntity $entity, $file, $width, $height, $mode, $optimize)
 {
     $transformation = new \Imagine\Filter\Transformation();
     if ($optimize) {
         // Optimize for web and rotate the images (after thumbnail creation).
         $transformation->add(new \Imagine\Filter\Basic\Autorotate(), 101)->add(new \Imagine\Filter\Basic\WebOptimization(), 2);
     }
     $watermark = $entity->getCollection()->getWatermark();
     if ($watermark === null) {
         // The image shall not be watermarked.
         return $transformation;
     }
     $imagine = $this->imagineManager->getImagine();
     // Check whether the image is big enough to be watermarked.
     if ($watermark->getMinSizeX() !== null && $width < $watermark->getMinSizeX()) {
         return $transformation;
     }
     if ($watermark->getMinSizeY() !== null && $height < $watermark->getMinSizeY()) {
         return $transformation;
     }
     // Generate the watermark image. It will already be correctly sized
     // for the thumbnail.
     if ($mode == 'outbound') {
         $wWidth = $width;
         $wHeight = $height;
     } elseif ($mode == 'inset') {
         $imageSize = getimagesize($file);
         $ratios = [$width / $imageSize[0], $height / $imageSize[1]];
         $wWidth = min($ratios) * $imageSize[0];
         $wHeight = min($ratios) * $imageSize[1];
     } else {
         throw new \LogicException();
     }
     $watermarkImage = $watermark->getImagineImage($imagine, $this->fontCollection, $wWidth, $wHeight);
     $watermarkSize = $watermarkImage->getSize();
     // Calculate watermark position. If the position is negative, handle
     // it as an offset from the bottom / the right side of the image.
     $x = $watermark->getPositionX();
     $y = $watermark->getPositionY();
     if ($x < 0) {
         $x += $wWidth - $watermarkSize->getWidth();
     }
     if ($y < 0) {
         $y += $wHeight - $watermarkSize->getHeight();
     }
     // If the watermark still exceeds the image's width or height, do
     // not watermark the image.
     // @todo Probably resize watermark instead?
     if ($x < 0 || $y < 0 || $x + $watermarkSize->getWidth() > $wWidth || $y + $watermarkSize->getHeight() > $wHeight) {
         return $transformation;
     }
     $point = new \Imagine\Image\Point($x, $y);
     $transformation->add(new \Imagine\Filter\Basic\Paste($watermarkImage, $point), 100);
     return $transformation;
 }