Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php longblob to img

Tags:

database

php

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?

like image 690
user1729425 Avatar asked Mar 31 '26 08:03

user1729425


1 Answers

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.

like image 116
Marc B Avatar answered Apr 02 '26 20:04

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!