4

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?

TMichel
  • 4,336
  • 9
  • 44
  • 67

1 Answers1

2

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(),
    ));
}
Adam Elsodaney
  • 7,722
  • 6
  • 39
  • 65
  • Thank you. Is throwing a warning `Warning: is_file() expects parameter 1 to be a valid path, string given` – TMichel Dec 15 '15 at 16:36
  • 1
    Sorry my bad -`BinaryFileResponse` expects the path to the image, not the content itself. Instead use `Response` (answer updated). – Adam Elsodaney Dec 15 '15 at 16:54