我有一个php代码,从数据库中检索图像并通过使用base64编码将其存储在json中。
$query=mysql_query("SELECT Id,Image FROM $table_first");
while ($row=mysql_fetch_assoc($query)) {
$array=$row;
$array['Image']=base64_encode($row['Image']);
$output[]=$array;
}
echo json_encode($output);
现在我有一个HTML文件,我必须解码该图像并将其显示在div元素中。我不知道如何解码这个图像。
$(document).ready(function(){
$.ajax({
url:"loc.php",
dataType:'json',
type:'POST',
success:function(output) {
}
});
});
</script>
</head>
<body>
<p> Test page </p>
<div class="Ch" id="Ch"></div>
这里我需要显示输出[0]。id为"ch"
直接在DATABASE中存储图像不是一个好主意。我推荐的一种方法是将图像直接存储在服务器中的特定位置,然后在数据库中插入图像的路径。用这种方法你可以避免很多麻烦。顺便说一下,你为什么要将图像编码为base_64?如何在数据库中存储图像?
未经测试(假设路径存储在数据库表中)
$query=mysql_query("SELECT Id,Image FROM $table_first");
while ($row=mysql_fetch_assoc($query)) {
$image=$row['Image'];
$id=$row['Id'];
$output=array("id"=>$id,"image"=>$image);
}
echo json_encode($output);
在你的ajax脚本中
$(document).ready(function(){
$.ajax({
url:"loc.php",
dataType:'json',
type:'POST',
success:function(output) {
var imagehtml='<img src="'+output.image+'" alt=""/>';
$("#Ch").html(imagehtml); //id of the div where you want the image
}
});
});
</script>
你可以使用(假设是png)<img src="data:image/png;base64,input_your_base64_from_database_here" />
有关详细信息,请查看Data_URI_scheme和如何显示图像。