dtkvlj5386 2019-03-20 13:15
浏览 824
已采纳

图像(Blob)在浏览器中只显示一次

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?

  • 写回答

1条回答 默认 最新

  • douniao7308 2019-03-20 14:30
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部