图像标签的SRC属性作为BLOB数据

5

我试图将存储在MySQL数据库中的图像(blob数据)与PHP链接起来,但我所做的只是得到一整页的字符。这是我做的事情:

$query = "SELECT image FROM uploads WHERE id = {$id}";
$image_array = mysql_query($query, $connection);
$row = mysql_fetch_array($image_array);
$image = $row['image'];

echo $image;
// echo base64_decode($content);

这将显示原始数据存储方式。我希望将其链接到HTML标签中,或者至少在页面上显示它,因为我还要显示很多其他内容,所以 header('Content-type: image/png'); 对我来说不是解决方案。

有什么建议吗?


你可以在这里找到你准确的SO答案。 - Smile
3个回答

8
为了正确显示图片,您只需要在echo之前放置一个带有Content-type: image/png的头即可。
header("Content-type: image/png");
echo (base64_decode($row['image']));

如果您想在图像标签中替换,请使用以下代码。
echo '<img src="data:image/png;base64,' . $row['image'] . '" />'; 

1

你需要提供适当的头部信息,否则页面将不知道你发送了什么内容。

// define results into variables 
$name=mysql_result($result,0,"file_name"); 
$size=mysql_result($result,0,"file_size"); 
$type=mysql_result($result,0,"file_type"); 
$content=mysql_result($result,0,"file_stream"); 

// give our picture the proper headers...otherwise our page will be confused 
header("Content-Disposition: attachment; filename=$name"); 
header("Content-length: $size"); 
header("Content-type: $type"); 
echo $content; 

0

你应该使用所谓的“内联图片”。 使用以下代码将图像显示在页面上,假设$image变量包含base64编码数据:

<img src="data:image/png;base64,<?php echo $image; ?>" alt="Larry" />

来源:https://zh.wikipedia.org/wiki/Data_URI_scheme


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接