简体   繁体   English

Symfony 3 - 在树枝扩展中提供图像

[英]Symfony 3 - Serve image within twig extension

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我想使用 php 提供一些在公共文件夹(网络)中不可用的图像,例如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.但它不起作用,因为返回的响应不是有效的 src 路径。

The only way I found is to base 64 encode the response returned我发现的唯一方法是对返回的响应进行 base 64 编码

<?php
return "data:image/jpeg;base64," . base64_encode($file);

So my question is how generate URL that target my twig extension?所以我的问题是如何生成针对我的树枝扩展名的 URL?

Something like path/to/twigExtension.php?ref=ref calls show(ref)类似path/to/twigExtension.php?ref=ref调用show(ref)

Maybe it's not the good way to achieve that.也许这不是实现这一目标的好方法。

This is a two step process.这是一个两步过程。

  1. you need to create to a valid link to each image (which will be a route to some kind of ImageController::show(id) controller-action)您需要创建到每个图像的有效链接(这将是某种ImageController::show(id)控制器动作的路由)

  2. The ImageController that takes the id (or imagename) and shouts out the binary content of the image file (or throws an error if a user is not granted to download the image). ImageController 接受 id(或图像名称)并输出图像文件的二进制内容(如果用户未被授权下载图像,则抛出错误)。 You can return a BinaryFileResponse here.您可以在此处返回 BinaryFileResponse。 Take a look here .看看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM