Php : Convert a blob into an image file
Is this possible with php and a mysql database to Convert a blob into an image file?
Solution 1:
You can use a few different methods depending on what php image library you have installed. Here's a few examples.
Note, the echo <img> is just a trick I use to display multiple images from the same php script when looping through a MySQL result resource. You could just as well output via header() as @NAVEED had shown.
GD:
$image = imagecreatefromstring($blob);
ob_start(); //You could also just output the $image via header() and bypass this buffer capture.
imagejpeg($image, null, 80);
$data = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/jpg;base64,' . base64_encode($data) . '" />';
ImageMagick (iMagick):
$image = new Imagick();
$image->readimageblob($blob);
echo '<img src="data:image/png;base64,' . base64_encode($image->getimageblob()) . '" />';
GraphicsMagick (gMagick):
$image = new Gmagick();
$image->readimageblob($blob);
echo '<img src="data:image/png;base64,' . base64_encode($image->getimageblob()) . '" />';
Solution 2:
If the BLOB contains the binary data of an image (in a recognizable format like e.g. tiff, png, jpeg, etc), take the content of the BLOB, write it to a file, and voilà... you got an image.
On some strange operation systems you have to give the output file a correspondig extension, so that the image file can be recognised as such.
Solution 3:
In my case i had to use base64_decode to convert blob images correctly into file.
$path = "/tmp/images";
$sql = "SELECT image_name, image_content FROM images";
$result = mysql_query($sql, $db_con);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$image = $row["image_contents"];
$name = $row["image_name"];
// option 1
$file = fopen($path."/".$name,"w");
echo "File name: ".$path."$name\n";
fwrite($file, base64_decode($image));
fclose($file);
// option 2 (oneliner)
// file_put_contents($path."/".$name, base64_decode($image));
}