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
Release: 2024-12-10 17:21:10
Original
374 people have browsed it

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>';
Copy after login

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;
?>
Copy after login

In your HTML:

<img src="image.php?id=<?php echo $image_id; ?>" />
Copy after login

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');
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template