Home >Database >Mysql Tutorial >How to Display BLOB Images from MySQL in PHP: Base64 Encoding vs. Separate Image File?
How to Display BLOB Images from MySQL Database in PHP
You are trying to display BLOB images from a MySQL database in PHP but encountering errors. Let's explore two options to solve the issue:
Option 1: Inline Base64 Encoding
echo '<dt><strong>Technician Image:</strong></dt><dd>'; echo '<img src="data:image/jpeg;base64,' . base64_encode($row2['image']) . '" width="290" height="290">'; echo '</dd>';
This method encodes the BLOB image into a base64 string and embeds it directly into the HTML. However, this approach is not recommended for large numbers of images.
Option 2: Image Output PHP File
Create an image.php file with the following code:
<?php $id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? intval($_GET['id']) : 0; $image = getImageFromDatabase($id); // Your function to fetch the image from the database header('Content-Type: image/jpeg'); echo $image; ?>
In your HTML:
<img src="image.php?id=<?php echo $image_id; ?>" />
This method retrieves the image from the database and sends it directly to the browser, ensuring the correct MIME type is set (image/jpeg). The header line:
header('Content-Type: image/jpeg');
instructs the browser to interpret the output as an image and display it accordingly. This eliminates the binary JPEG data issue you were experiencing.
The above is the detailed content of How to Display BLOB Images from MySQL in PHP: Base64 Encoding vs. Separate Image File?. For more information, please follow other related articles on the PHP Chinese website!