PHP – Display a Base64 Image From Database in HTML

This PHP example shows you how to display a base64 image from database in HTML.

To do this, you first need to convert the image to base64 using base64_encode function. Then specify the correct content type, content encoding, and base64 data in the src attribute like this:

<img src="data:image/jpeg;base64,<base64-data>

See the below example for more details:

// Step 1: Convert the image to base64 and save it in database
$imagePath = 'D:/path/to/your-image.jpg';

$image = file_get_contents($imagePath);
$base64Image = base64_encode($image)

// In the '$database->save' below, it is just a simulation function,
// that saves data in database. You should replace it with your exact function.

// Step 2: Display the saved base64 image in HTML
$savedBase64Image = $database->getBase64Image(); // it is just a simulation function

echo '<img src="data:image/jpeg;base64,' . $savedBase64Image . '">';

0 0 vote
Article Rating
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x