public function transform(EventInterface $event)
{
$image = $event->getArgument('image');
$params = $event->getArgument('params');
$width = !empty($params['width']) ? (int) $params['width'] : 0;
$height = !empty($params['height']) ? (int) $params['height'] : 0;
$imageIdentifier = !empty($params['img']) ? $params['img'] : $this->defaultImage;
$position = !empty($params['position']) ? $params['position'] : $this->position;
$x = !empty($params['x']) ? (int) $params['x'] : $this->x;
$y = !empty($params['y']) ? (int) $params['y'] : $this->y;
$opacity = (!empty($params['opacity']) ? (int) $params['opacity'] : 100) / 100;
if (empty($imageIdentifier)) {
throw new TransformationException('You must specify an image identifier to use for the watermark', 400);
}
// Try to load watermark image from storage
try {
$watermarkData = $event->getStorage()->getImage($event->getRequest()->getUser(), $imageIdentifier);
$watermark = new Imagick();
$watermark->readImageBlob($watermarkData);
$watermarkSize = $watermark->getImageGeometry();
$watermark->setImageOpacity($opacity);
} catch (StorageException $e) {
if ($e->getCode() == 404) {
throw new TransformationException('Watermark image not found', 400);
}
throw $e;
}
// Should we resize the watermark?
if ($height || $width) {
// Calculate width or height if not both have been specified
if (!$height) {
$height = $watermarkSize['height'] / $watermarkSize['width'] * $width;
} else {
if (!$width) {
$width = $watermarkSize['width'] / $watermarkSize['height'] * $height;
}
}
$watermark->thumbnailImage($width, $height);
} else {
$width = $watermarkSize['width'];
$height = $watermarkSize['height'];
}
// Determine placement of the watermark
if ($position === 'top-right') {
$x = $image->getWidth() - $width + $x;
} else {
if ($position === 'bottom-left') {
$y = $image->getHeight() - $height + $y;
} else {
if ($position === 'bottom-right') {
$x = $image->getWidth() - $width + $x;
$y = $image->getHeight() - $height + $y;
} else {
if ($position === 'center') {
$x = $image->getWidth() / 2 - $width / 2 + $x;
$y = $image->getHeight() / 2 - $height / 2 + $y;
}
}
}
}
// Now make a composite
try {
$this->imagick->compositeImage($watermark, Imagick::COMPOSITE_OVER, $x, $y);
$image->hasBeenTransformed(true);
} catch (ImagickException $e) {
throw new TransformationException($e->getMessage(), 400, $e);
}
}