I\'m using the LiipImagineBundle with Symfony 2.1 and would like to resize user uploaded images upon upload before saving them to the permanent filesystem location (to strip
Modified version of @Peter Wooster, and made it more generic so if someone is using it without Image entity he/she can easily take benifet from it. I'm giving here two versions, one that can be used kept in utility or non-controller class. And the other version is for controller classes. It's up to you now where you like :)
To use outside of controller e.g. keeping it in utility classes
/**
* Write a thumbnail image using the LiipImagineBundle
*
* @param Document $fullSizeImgWebPath path where full size upload is stored e.g. uploads/attachments
* @param string $thumbAbsPath full absolute path to attachment directory e.g. /var/www/project1/images/thumbs/
* @param string $filter filter defined in config e.g. my_thumb
* @param Object $diContainer Dependency Injection Object, if calling from controller just pass $this
*/
public function writeThumbnail($fullSizeImgWebPath, $thumbAbsPath, $filter, $diContainer) {
$container = $diContainer; // the DI container, if keeping this function in controller just use $container = $this
$dataManager = $container->get('liip_imagine.data.manager'); // the data manager service
$filterManager = $container->get('liip_imagine.filter.manager'); // the filter manager service
$image = $dataManager->find($filter, $fullSizeImgWebPath); // find the image and determine its type
$response = $filterManager->applyFilter($image, $filter);
$thumb = $response->getContent(); // get the image from the response
$f = fopen($thumbAbsPath, 'w'); // create thumbnail file
fwrite($f, $thumb); // write the thumbnail
fclose($f); // close the file
}
To use in controller e.g. CommonController or any other controller.
/**
* Write a thumbnail image using the LiipImagineBundle
*
* @param Document $fullSizeImgWebPath path where full size upload is stored e.g. uploads/attachments
* @param string $thumbAbsPath full absolute path to attachment directory e.g. /var/www/project1/images/thumbs/
* @param string $filter filter defined in config e.g. my_thumb
*/
public function writeThumbnail($fullSizeImgWebPath, $thumbAbsPath, $filter) {
$container = $this->container;
$dataManager = $container->get('liip_imagine.data.manager'); // the data manager service
$filterManager = $container->get('liip_imagine.filter.manager'); // the filter manager service
$image = $dataManager->find($filter, $fullSizeImgWebPath); // find the image and determine its type
$response = $filterManager->applyFilter($image, $filter);
$thumb = $response->getContent(); // get the image from the response
$f = fopen($thumbAbsPath, 'w'); // create thumbnail file
fwrite($f, $thumb); // write the thumbnail
fclose($f); // close the file
}