Return Image as http-response from Listener Symfony2
<p>This listener sends me reports on all kinds of exceptions that occur on the website. Sometimes I get reports of images that have been deleted but are still consulted by search engines and others. </p>

<p>I want to do, instead of displaying an error message " 404 Not Found " return the correct image. To do this I created a database table that stores the old links and new links of the images that have been deleted, moved or changed its name.</p>

<p>then, this listener find in db the links to fallen and gets the new links of images . The goal is to return the image as http-response with header content-type as image.</p>

<p>My code is:</p>

<pre><code>class ExceptionListener
{
private $service_container;
private $router;

function __construct(Container $service_container, $router){
    $this-&gt;service_container = $service_container;
    $this-&gt;router = $router;
}

public function onKernelException(GetResponseForExceptionEvent $event){
    $exception = $event-&gt;getException();
    $request = $this-&gt;service_container-&gt;get('request');

    ...

    $document_root = $request-&gt;server-&gt;get('DOCUMENT_ROOT');
    $filename = realpath($document_root . '/'. '/path/to/new_image.jpg');
    $response = new \Symfony\Component\HttpFoundation\Response();
    $response-&gt;headers-&gt;set('Content-type',  'image/jpeg');
    $response-&gt;headers-&gt;set('Content-Disposition', 'inline; filename="' . basename($filename) . '";');
    $response-&gt;headers-&gt;set('Content-length', filesize($filename));
    $response-&gt;sendHeaders();
    $response-&gt;setContent(file_get_contents($filename));
    return $response;

    ...
}
}
</code></pre>

<p>The following error occurs:</p>

<p><a href="https://i.stack.imgur.com/UQrjD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UQrjD.png" alt="browser screenshot"></a></p>

<p>In the browser you can see a small box , it is as if trying to show the image but the image source could not be obtained . But if the same code is testing on controller , its working properly and the image is displayed .</p>

<p><a href="https://i.stack.imgur.com/e2lxO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e2lxO.png" alt="in controller works fine"></a></p>

<p>What can I do to return image from a listener ? thanks</p>