Search code examples
symfonyliipimaginebundle

LiipImagineBundle and BinaryFileResponse


In my project i have some protected images outside the web root.

In my controller, i created a route that returns a BinaryFileResponse with the contents of the image i want to show:

    /**
     * @Route("/protected/images/{filename}", name="protected_image")
     */
    public function getProtectedimage($filename)
    {
        //.. logic ..
        return new BinaryFileResponse($path);
    }

In my template i use Twig's path() to render that route and show the image:

 <img src="{{ path('protected_image',{filename: myEntity.imagePath}) }}">

Now, i want to use that route together with LiipImagine to apply a filter and create thumbnails, like so:

<img src="{{ path('protected_image',{filename: myEntity.imagePath}) | imagine_filter('my_thumb_filter') }}">

The problem: always shows broken image and Source image not found in .. in logs.

Can i use LiipImagine together with a route that returns BinaryFileResponse? If so, how?


Solution

  • You could apply the filter before returning the response. This solution is not efficient however, because it applies the fitler on every request, so utilize the CacheManager in the bundle. (I'm still figuring out if it works for non-public images.)

    /**
     * @Route("/protected/images/{filename}", name="protected_image")
     */
    public function getProtectedimage($filename)
    {
        //.. logic ..
    
    
        /** @var \Liip\ImagineBundle\Binary\Loader\FileSystemLoader $loader */
        $loader = $this->get('liip_imagine.binary.loader.filesystem');
    
        /** @var \Liip\ImagineBundle\Imagine\Filter\FilterManager $filterManager */
        $filterManager = $this->get('liip_imagine.filter.manager');
    
        $filteredImageBinary = $filterManager->applyFilter(
            $loader->find('path/to/image'),
            'my_thumb_filter'
        );
    
        return new Response($filteredImageBinary->getContent(), 200, array(
            'Content-Type' => $filteredImageBinary->getMimeType(),
        ));
    }