我试图以base64编码格式显示图像。我为此编写了以下php代码。但它只显示尺寸为20px x 20px的空白图像。如何更正此代码段?
<?php
$username = "root";
$password = "";
$host = "localhost";
$connector = mysql_connect($host, $username, $password) or die("Unable to connect");
$selected = mysql_select_db("postman", $connector) or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT image FROM mail ");
?>
这是连接代码,下面是为在该表中显示图像而创建的表.......
<table border="2" id="tblData" bgcolor="#ACAAFC" align="center">
<thead>
<tr >
<th><h4>IMAGE</h4></th>
</tr>
</thead>
<tbody>
</tbody>
这是循环体中的基本运行,其中正在获取和显示图像,但是在执行代码时未使用函数base64_decode显示图像。以便解码图像串数组。
<?php
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>"
$row['image'];
$str = implode(';', $row);
$imgstr = "image/jpeg;base64,$str";
$new_data = explode(";", $imgstr);
$type = $new_data[0];
$data = explode(",", $new_data[1]);
header("Content-type:" . $type);
echo "<td>" . base64_decode($data[1]) . "</td>";
echo "</tr>";
"</table>";
}
?>
</tbody>
</table>
</form>
<?php mysql_close($connector); ?>
答案 0 :(得分:0)
假设你正在使用PDO扩展,那么cose应该是这样的(show_image.php可以是文件的名称):
<?php
$where = dirname(__FILE__);
include($where . "/config/db.php"); // here you'll have the param to connect to db
$query = "SELECT image FROM mail ";
$stmt = $dbh->query($query);
if($stmt->rowCount() > 0)
{
$data = $stmt->fetch(PDO::FETCH_ASSOC); //FETCH ASSOC IS NOT NEEDED, but it should works anyway
$image = $data['image'];
$type = $data['type'];
header("Content-type: ".$type);
echo $image;
}
else
{
// show another (default) image maybe
}
?>
当您需要显示图像时,您可以这样做:
<img src="show_image.php" />
如果你需要将param传递给show_image.php文件,例如从特定的id获取图像,你应该这样做:
<img src="show_image.php?id=1 /> // Assuming the id you need is "1"
db.php文件应该是这样的:
<?php
$user = "your username";
$password = "password";
$host = "localhost or your host anyway";
$dbname = "postman";
$dbh = null;
try {
$dbh = new PDO ("mysql:host=" . $host . ";dbname=" . $dbname, $user, $password);
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
答案 1 :(得分:0)
你遇到的问题是你混淆了为HTML页面提供服务的代码和为图像提供服务的代码。
传统上,您需要两个脚本:
另一种方法是使用data:
scheme URLs。这意味着将图像包含在HTML本身中,并带有以下形式的标记:
<img src="data:image/png;base64,<base 64 encoded image data here>" alt="whatever">
由于您的图像已经是Base 64编码,当然您不需要对它们进行解码/重新编码。