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 in PHP: Base64 Encoding vs. Separate Image File?

DDD
DDDOriginal
2024-12-10 17:21:10354browse

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']) &amp;&amp; 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn