Home >Database >Mysql Tutorial >How to Correctly Display Image BLOBs from MySQL in PHP?

How to Correctly Display Image BLOBs from MySQL in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 12:47:14595browse

How to Correctly Display Image BLOBs from MySQL in PHP?

PHP Display Image BLOB from MySQL

When attempting to display an image stored in a MySQL BLOB column, some users encounter issues where Chrome or IE display an image icon instead of the actual image. This can be due to the lack of proper encoding and the handling of the binary image data.

Solution

The correct way to display an image BLOB in PHP involves:

  • Preparing the Data:

    • Retrieve the image data from the MySQL database using a query (e.g., SELECT * FROM products WHERE id = ?).
    • Store the retrieved image data in a variable (e.g., $image).
  • Encoding the Binary Data:

    • Use the base64_encode() function to convert the binary image data into a base64-encoded string. This step is necessary to encode the binary data into a format suitable for displaying as an image.
  • Displaying the Image:

    • Set the appropriate HTTP header to specify the image type (e.g., image/jpeg).
    • Output the base64-encoded image data as the image source. For example:
    header("Content-Type: image/jpeg");
    echo '<img src="data:image/jpeg;base64,' . base64_encode($image) . '" />';

Note: Ensure that the image data retrieved from the database is valid and that there are no trailing whitespace characters before or after the tags.

The above is the detailed content of How to Correctly Display Image BLOBs from MySQL in PHP?. 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