I want to serve several images which are not avaible in public folder (web) using php for example path/to/myphp/script.php?image=imagereference&some=parameter
To improve performances and not using this approach I made a twig extension to do that.
<?php
#src/MyBundle/Service/DisplayImage.php
namespace MyBundle\Service;
#https://symfony.com/blog/new-in-symfony-2-4-the-request-stack
use Symfony\Component\HttpFoundation\RequestStack;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
class DisplayImage
{
private $entityManagerInterface;
private $requestStack;
public function __construct(EntityManagerInterface $entityManagerInterface, RequestStack $requestStack)
{
$this->entityManagerInterface = $entityManagerInterface;
$this->requestStack = $requestStack;
}
public function show(int $ref)
{
$photoPath = __DIR__ ."/../photoFolder/".$ref.".jpg";
$file = file_get_contents($photoPath);
$response = new Response();
$response->headers->set('Content-Type', 'image/jpeg');
$response->setContent($file);
return $response;
}
}
And into my twig template
{# src/MyBundle/Ressources/views/DisplayImage.html.twig #}
{% for ref in refs %}
<img src="{{ show(ref) }}"/>
{% endfor %}
But it doesn't work because the response returned is not a valid src path.
The only way I found is to base 64 encode the response returned
<?php
return "data:image/jpeg;base64," . base64_encode($file);
So my question is how generate URL that target my twig extension?
Something like path/to/twigExtension.php?ref=ref
calls show(ref)
Maybe it's not the good way to achieve that.