使用PHP和MySQL数据库是否可以将blob转换为图像文件?
使用PHP和MySQL数据库是否可以将blob转换为图像文件?
根据您安装的php图像库,可以使用几种不同的方法。以下是一些示例。
请注意,echo <img> 只是我用来在循环遍历MySQL结果资源时显示多个图像的技巧。就像@NAVEED所展示的那样,您也可以通过header()输出。
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()) . '" />';
在我的情况下,我必须使用base64_decode将blob图像正确转换为文件。
$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));
}
如果你正在将图片存储在MySql表的Blob字段中,并且想要获取这些图片,那么这篇文章对你来说会很有用:
请看上述文章中的以下部分:
<?php
if(isset($_REQUEST['id']))
{
// get the file with the id from database
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
$id = $_ REQUEST ['id'];
$query = "SELECT `img_name`, `img_type`, `img_size`, `img_data`
FROM img_tbl WHERE id = ‘$id’";
$result = mysql_query($query) or die(mysql_error());
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
print $content;
mysql_close($dbconn);
}
?>