图片(Blob)在浏览器中仅显示一次 [英] Image (Blob) showing only once in browser

查看:167
本文介绍了图片(Blob)在浏览器中仅显示一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Symfony2和Twig:

I'm using Symfony2 and Twig:

在实体类中

/**
 * @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()));
}

在视图中

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

但是如果我写

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

然后,浏览器仅在第一次显示它. 在浏览器(Firefox)中,DOM如下所示:

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,">

因此第二个img标签中没有图像内容.

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

有什么想法可以多次显示图像吗?

Any idea how to show the image more than once?

推荐答案

您将需要

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()));
}

也许为了提高性能,可以使用一个属性来存储blob的原始内容:

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;
}

这篇关于图片(Blob)在浏览器中仅显示一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆