Display image stored in BLOB database in symfony

前端 未结 4 1006
温柔的废话
温柔的废话 2021-01-21 10:19

I load my image (blob data ) in my GETer Entity When I just return ($this->foto) in my GETer I see :Resource id #284 on the screen When I change my GETer like this : return stre

相关标签:
4条回答
  • 2021-01-21 10:28

    in your entity write your image getter like this:

    public function getFoto()
    {
        return imagecreatefromstring($this->foto);
    }
    

    and use it instead of the object "foto" property.

    php doc for the function: http://php.net/manual/de/function.imagecreatefromstring.php

    0 讨论(0)
  • 2021-01-21 10:43

    A more direct way, without extra work in the controller:

    In the Entity Class

    /**
     * @ORM\Column(name="photo", type="blob", nullable=true)
     */
    private $photo;
    
    private $rawPhoto;
    
    public function displayPhoto()
    {
        if(null === $this->rawPhoto) {
            $this->rawPhoto = "data:image/png;base64," . base64_encode(stream_get_contents($this->getPhoto()));
        }
    
        return $this->rawPhoto;
    }
    

    In the view

    <img src="{{ entity.displayPhoto }}">
    

    EDIT

    Thanks to @b.enoit.be answer to my question here, I could improve this code so the image can be displayed more than once.

    0 讨论(0)
  • 2021-01-21 10:52

    As it is said before you must use base64 method, but for a better performance and usability, the correct option is creating a custom twig filter (Twig extension) as described here .

    <?php
    
    
    namespace Your\Namespace;
    
    
    use Twig\Extension\AbstractExtension;
    use Twig\TwigFilter;
    
    class TwigExtensions extends AbstractExtension
    {
        public function getFilters()
        {
            return [
                new TwigFilter('base64', [$this, 'twig_base64_filter']),
            ];
        }
    
        function twig_base64_filter($source)
        {   if($source!=null) {           
               return base64_encode(stream_get_contents($source));
            }
            return '';
        }
    }
    

    In your template:

    <img src="data:image/png;base64,{{ entity.photo | base64 }}">
    
    0 讨论(0)
  • 2021-01-21 10:53

    You are using <img src="(raw image)"> instead of <img src="(image's url)">

    A quick solution is to encode your image in base64 and embed it.

    Controller

    $images = array();
    foreach ($entities as $key => $entity) {
      $images[$key] = base64_encode(stream_get_contents($entity->getFoto()));
    }
    
    // ...
    
    return $this->render('CustomCMSBundle:Producten:index.html.twig', array(
        'entities' => $entities,
        'images' => $images,
    ));
    

    View

    {% for key, entity in entities %}
      {# ... #}
      <img alt="Embedded Image" src="data:image/png;base64,{{ images[key] }}" />
      {# ... #}
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题