<?php
namespace Jabber\RestApiBundle\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\GenericEvent;
class ThumbnailListener {
public function onRequest(RequestEvent $e) {
$pathInfo = $e->getRequest()->getPathInfo();
if (str_contains($pathInfo, 'image-thumb') && str_contains($pathInfo, 'dynamic')) {
if (!file_exists(PIMCORE_WEB_ROOT . '/var/tmp/thumbnails' . $pathInfo)) {
$pathParts = explode("/", $pathInfo);
$thumb = $pathParts[count($pathParts)-2];
$thumbParts = explode("__", $thumb);
$configName = $thumbParts[count($thumbParts)-1];
$assetId = $pathParts[count($pathParts)-3];
$thumbPath = $this->generateThumbnail($assetId, $configName);
if (!empty($thumbPath)) {
$response = new Response();
$response->headers->set('Content-Type', 'image/png');
$response->setContent(file_get_contents($thumbPath));
$e->setResponse($response);
}
}
}
}
public function generateThumbnail($assetId, $configName) {
$config = null;
$image = \Pimcore\Model\Asset\Image::getById($assetId);
$thumbnail = new \Pimcore\Model\Asset\Image\Thumbnail\Config();
$properties = $image->getProperties();
$configPrefix = explode("-", $configName)[0];
if (isset($properties[$configPrefix . '_height'])) {
$config = [
'width' => $properties[$configPrefix . '_width']->getData(),
'height' => $properties[$configPrefix . '_height']->getData(),
'x' => $properties[$configPrefix . '_x']->getData(),
'y' => $properties[$configPrefix . '_y']->getData(),
];
}
if (!empty($config)) {
$thumbnail->addItem('crop', $config);
$thumbnail->setName($configName);
$newImage = $image->getThumbnail($thumbnail, false);
return PIMCORE_WEB_ROOT . '/var/tmp/thumbnails' . $newImage->getPath();
}
}
}