Silex + Twig + SQL Server:渲染图片

时间:2016-05-12 08:42:18

标签: database image twig silex

我在BLOB列的SQL Server数据库中有一些图片。

我需要获取它们并显示到HTML页面。

但是在HTML页面的结果中,我在src属性中有长字符串而不是图片。

Silex代码:

<!-- language-all: php -->
$pict->get('/show_pic/{id}', function ($id) use ($app) {
        //Request of photos
        $photos=getPhotoByID($id, $app);
        return $app['twig']->render('test/template_show_pictures.html.twig', array('photos'=>$photos));
})->bind('show_pic');

function getPhotoByID($ID, $app)
{
        $sql = "<some SQL here>";
        $statement = $app['dbs']['mssql']->prepare($sql);
        $statement->bindValue(1, $ID, "text");
        $statement->execute();
        $photo = $statement->fetchAll();

        if (empty($photo)) {
            return "We don't have a photo with id=".$ID;
        }

        return $photo;
}

Twig文件:

<!-- language: twig -->
    {% extends 'test/test_base.html.twig' %}
    {% block title %}Pictures from DB{% endblock %}
    {% block content %}
    {% for im in photos %}
      <img alt="Embedded Image" src="data:image/jpeg;base64,{{ im['Foto'] }}" />
    {% endfor %}
    {% endblock %}

HTML标记:

<!-- language: lang-html -->
<!DOCTYPE html>
<html>
    <head>
        <title>Pictures from DB</title>
            <link rel="stylesheet" href="/css/print.css">
        </head>
    <body>
    <div class="page">
      <img alt="Embedded Image" src="data:image/jpeg;base64,���JFIF...too many symbols here" />
            </div>
    </body>
</html>

它出了什么问题?

1 个答案:

答案 0 :(得分:2)

您应该使用base64编码图像

将用于编码的过滤器添加到base64:

<?php
     $password = "<!\\\\*$troll'*\\\#!>";

     echo "<pre>";
     echo htmlentities($password); 
     echo "</pre>";

并在模板中使用它:

$app->extend('twig', function ($twig, $app) {
    $twig->addFilter('base64_encode', new \Twig_SimpleFilter('base64_encode', function ($value) {
        return \base64_encode($value);
    }));

    return $twig;
});