Php longblob to img

use*_*425 3 php database

我有一个函数调用数据库类,并要求一个图像列表.以下是该功能.

//Hämtar en array av filer från disk.
public function GetFiles()
{   

    $sql = "SELECT pic FROM pictures";
    $stmt = $this->database->Prepare($sql);

    $fileList = $this->database->GetAll($stmt);
    echo $fileList;
    if($fileList)
    {
        return $fileList;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

这是GetFiles调用的数据库类方法.

public function GetAll($sqlQuery) {

        if ($sqlQuery === FALSE)
        {
            throw new \Exception($this->mysqli->error);
        }
        //execute the statement
        if ($sqlQuery->execute() == FALSE)
        {
            throw new \Exception($this->mysqli->error);
        }
        $ret = 0;
        if ($sqlQuery->bind_result($ret) == FALSE)
        {
            throw new \Exception($this->mysqli->error);
        }

        $data = array();
        while ($sqlQuery->fetch())
        {
            $data[] = $ret;
            echo $ret;
        }

        $sqlQuery->close();

        return $data;
    }
Run Code Online (Sandbox Code Playgroud)

然后,GetFiles函数返回值由另一个函数处理

public function FileList($fileList)
{
    if(count($fileList) == 0)
    {
        return "<p class='error'> There are no files in array</p>";
    }

    $list = '';
    $list .= "<div class='list'>";
    $list .= "<h2>Uploaded images</h2>";
    foreach ($fileList as $file) {

        $list .= "<img src=".$file." />";
    }
    $list .= "</div>";
    return $list;
}
Run Code Online (Sandbox Code Playgroud)

但是我的数据库只是返回longblob作为很多carachters,我如何让longblob显示为图像?

Mar*_*c B 5

您需要对其进行base64编码并通过数据URI传递它,例如

<img src="data:image/jpeg;base64,<?php echo base64_encode($file) ?>" />
Run Code Online (Sandbox Code Playgroud)

但是,如果你正在提供"大"图片,这将会产生一个非常臃肿的页面,绝对无法缓存图像数据以便以后为用户节省下载流量.使用明确的图像服务脚本会更好,例如

<img src="getimage.php?imageID=XXX" />
Run Code Online (Sandbox Code Playgroud)

然后在该脚本中包含您的db代码:

$blob = get_image_data($_GET[xxx]);
header('Content-type: image/jpeg');
echo $blob;
Run Code Online (Sandbox Code Playgroud)

这样的问题是为什么从数据库中提供图像通常是个坏主意.