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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 03:55:02599browse

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

Converting a Blob into an Image File in PHP

PHP provides various methods for converting BLOB data stored in a MySQL database into an image file. These methods rely on different image libraries that may already be installed on your system. Here are several options:

GD Library

<?php
$image = imagecreatefromstring($blob); 

ob_start(); 
imagejpeg($image, null, 80);
$data = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/jpg;base64,' .  base64_encode($data)  . '" />';
?>

ImageMagick (iMagick) Library

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

GraphicsMagick (gMagick) Library

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

Notes:

  • The echo trick used in the examples displays multiple images when iterating through a MySQL result resource. Alternatively, you can use header() to output the image directly.
  • The selected method will depend on the specific image library installed on your system.

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