catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.83k stars 1.15k forks source link

Get BLOB image and apply base64_encode before encoding it to JSON #400

Closed Nicero closed 7 years ago

Nicero commented 8 years ago

I have some images saved into BLOB. I can retrieve the images like this:

$datas = $database->select("images", [
    "title",
    "image"
], [
    "id[>=]" => 1
]);

and display them with PHP like this:

echo '<img src="data:image/jpeg;base64,'.base64_encode($data['image']).'"/>';

Now I would like to send the result query via Ajax in JSON format and then display the image using Javascript. The following code works fine for text fields but not for images saved into BLOB:

$a = $_GET['jsoncallback'] . '(' . json_encode($datas) . ');';
echo $a;

because at the images is not applied base64_encode first .

How do I add base64_encode to image before sending it to json_encode using Medoo?

catfan commented 8 years ago

You can encode and decode the BLOB image content yourself for saving and fetching data for database.

BTW, I think it is not a good idea to save image content into database. Using file system or third-party image storage provider is better.

Nicero commented 8 years ago

Thank for the fast answer. Encoding the image before adding it to a BLOB worked fine:

$blob = file_get_contents("Image00001.jpg");

$last_user_id = $database->insert("images", [
    "image" => base64_encode($blob_01)
]);

Read the image from dB:

$datas = $database->select("images", [
    "image"
], [
    "id[>=]" => 1
]);

$a = $_GET['jsoncallback'] . '(' . json_encode($datas) . ');';

echo to Ajax:

echo $a;