Home >Database >Mysql Tutorial >How to Convert a MySQL BLOB Field to an Image File in PHP?

How to Convert a MySQL BLOB Field to an Image File in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 18:51:02329browse

How to Convert a MySQL BLOB Field to an Image File in PHP?

Convert a MySQL Blob Field to an Image File in PHP

In PHP, you can convert data stored as a BLOB (Binary Large Object) field in a MySQL database into an image file. This is useful for displaying images on web pages or storing them in a file system.

Here are three methods you can use, depending on the PHP image library you have installed:

GD Library:

$image = imagecreatefromstring($blob);

ob_start(); // Capture the output buffer
imagejpeg($image, null, 80);
$data = ob_get_contents();
ob_end_clean();

echo '<img src="data:image/jpg;base64,' . base64_encode($data) . '" />';

ImageMagick Library (iMagick):

$image = new Imagick();
$image->readimageblob($blob);
echo '<img src="data:image/png;base64,' . base64_encode($image->getimageblob()) . '" />';

GraphicsMagick Library (gMagick):

$image = new Gmagick();
$image->readimageblob($blob);
echo '<img src="data:image/png;base64,' . base64_encode($image->getimageblob()) . '" />';

In these examples, the echo statement uses data URIs to display the images inline. Alternatively, you can use the header() function to output the image directly to the browser:

header('Content-Type: image/jpeg');
echo $data;

The above is the detailed content of How to Convert a MySQL BLOB Field to an Image File 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