How to read images from MySQL database using PHP?
If the images are stored in a BLOB in the database, how to use the binary data that I get and turn it into an image
What you should probably do, if storing images as BLOBs, is provide a URL that calls your script in a way that it can determine what image to return.
Use that URL as the src
, or background-image: url(...)
and in the script, read the BLOB from the database in to a variable.
Then output the variable after appropriate header information, telling the browser it is to receive an image, for instance:
header('Content-Type: image/jpeg');
Sending a Content-Length
header and sensible information on caching/expiry would also be wise.
NB. Having said all that, I tend to be wary of using BLOBs in databases, they tend to cripple performance. When I want to store images, I store then in some directory structure and reference them in the database in some fashion.
To directly use the binary data as a an image source, you can use the data URI scheme, for example:
$uri = 'data:image/png;base64,'.base64_encode($row['binary-data']);
This URI can then be used directly as the image’s source:
background-image: url(<?php echo $uri; ?>)
<img src="<?php echo $uri; ?>">
But that has some substantial disadvantages: Besides the lack of support for these data URIs in older browsers, data URIs do also have disadvantaged regarding payload, caching, and references.