2

I'm using Symfony2 and Twig:

In the Entity Class

/**
 * @ORM\Column(name="photo", type="blob", nullable=true)
 */
private $photo;

// ...

public function displayPhoto()
{
    return "data:image/png;base64," . base64_encode(stream_get_contents($this->getPhoto()));
}

In the view

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

But if I write

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

Then the browser display it only the first time. In the browser (Firefox) The DOM looks like this:

<img src="data:image/png;base64,/9j/4QS...//much more chars//...f7R+ooYz//Z">
<img src="data:image/png;base64,">

So the image content is not present in the second img tag.

Any idea how to show the image more than once?

Roubi
  • 1,989
  • 1
  • 27
  • 36
  • `stream_get_contents($this->getPhoto())` repeatable? – ficuscr Mar 20 '19 at 21:22
  • 3
    I would expect it's because you can't read the stream twice (see http://php.net/manual/en/function.stream-get-contents.php - it reads to the end of the buffer from wherever it's up to now. So the second time "wherever it's up to now" will already be the end.). But wanting to read from the stream twice is bad anyway, it's not efficient. If you think you'll need the data more than once, store it in a variable after you've read the stream, and use that variable as the thing you repeatedly reference. – ADyson Mar 20 '19 at 21:56

1 Answers1

3

You will need to either rewind your stream

/**
 * @ORM\Column(name="photo", type="blob", nullable=true)
 */
private $photo;

public function displayPhoto()
{
    rewind($this->getPhoto());
    return "data:image/png;base64," . base64_encode(stream_get_contents($this->getPhoto()));
}

Or maybe better for performance, have a property storing the raw content of the blob:

/**
 * @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;
}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83