Home > Database > Mysql Tutorial > body text

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

Patricia Arquette
Release: 2024-11-11 18:51:02
Original
291 people have browsed it

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

ImageMagick Library (iMagick):

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

GraphicsMagick Library (gMagick):

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template