Reputation: 131
I have a function that calls on a database class, and asks for a list of images. This below is the function.
//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;
}
And this is my database class method that GetFiles calls.
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;
}
The GetFiles function return value is then later processed by another function
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;
}
But my database just returns the longblob as a lot of carachters, how do i get the longblob to display as images?
Upvotes: 3
Views: 6197
Reputation: 95131
I would advise you to save the image to the filesystem and load from there for the following reasons:
Look into a CDN option.
If you insist
$list = sprintf("<img src=\"data:image/jpeg;base64,%s\" />",base64_encode($file));
Upvotes: 0
Reputation: 360762
You'd need to base64 encode it and pass it in via a data URI, e.g.
<img src="data:image/jpeg;base64,<?php echo base64_encode($file) ?>" />
However, if you're serving up "large" pictures, this is going to make for a hideously bloated page, with absolutely no way to cache the image data to save users the download traffic later on. You'd be better off with an explicitly image-serving script, e.g.
<img src="getimage.php?imageID=XXX" />
and then have your db code in that script:
$blob = get_image_data($_GET[xxx]);
header('Content-type: image/jpeg');
echo $blob;
Problems like this are why it's generally a bad idea to serve images out of a database.
Upvotes: 5
Reputation: 324750
If you're embedding it as part of a webpage, then you should use the data
URI scheme.
Better would be to have the <img>
tag point to a PHP file that sets the correct Content-Type
header and dumps the image data.
Upvotes: 1