Displaying BLOB Images from MySQL Database
In your quest to display BLOB images from your MySQL database, you've encountered an issue where your PHP page shows the image as binary data instead of an actual image. Let's delve into the solution to resolving this.
The error you're seeing stems from the lack of a proper "Content-Type" header declaration. This header informs the browser about the expected data type of the response. In your case, you need to specify that the response is an image of type "image/jpeg."
Inline Base64 Encoding (Recommended for Limited Images)
For a small number of images, you can utilize inline base64 encoding. Here's how you can implement it:
echo '<dt><strong>Technician Image:</strong></dt><dd>' . '<img src="data:image/jpeg;base64,' . base64_encode($row2['image']) . '" width="290" height="290">' . '</dd>';
Creating an Image PHP File (Recommended for Numerous Images)
If you have a large number of images to display, a better approach is to create a separate PHP file that handles the image retrieval and output. Your HTML and PHP files would look like this:
HTML:
<img src="image.php?id=<?php echo $image_id; ?>" />
PHP:
<?php $id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? intval($_GET['id']) : 0; $image = getImageFromDatabase($id); // your code to fetch the image header('Content-Type: image/jpeg'); echo $image; ?>
By specifying the "Content-Type" header correctly, you will instruct the browser to render the data as an image, solving your display issue.
The above is the detailed content of How to Display BLOB Images from a MySQL Database in PHP?. For more information, please follow other related articles on the PHP Chinese website!