从MySQL服务器解码Base64映像


Decode Base64 image from MySQL server

我使用Base64对图像进行编码,将图像作为BLOB存储在在线MySQL数据库中。我对储蓄没有问题。但我无法从服务器上检索图像。它们似乎坏了。我相信这是因为它没有被解码。

我尝试手动将几张照片上传到服务器,由于它们没有编码,所以可以正确检索。这是我用来检索图像的代码。有人能告诉我如何解码图像吗?

<?php
$db = mysql_connect("localhost","un","pw") or die(mysql_error()); 
mysql_select_db("datab",$db) or die(mysql_error()); 
$userId = $_GET['eid']; 
$query = "SELECT image FROM event WHERE eid='$userId'"; 
$result = mysql_query($query) or die(mysql_error()); 
$photo = mysql_fetch_array($result); 
header('Content-Type:image/png;base64'); 
echo $photo['image']; 
?>

首先,请注意mysql语法已经过时,完全不推荐使用!请改用mysqli或PDO!

然后,按照你的代码,你只需要在html文件中调用你的图像,就像这样:

<img src="data:image/png;base64, <?php echo $photo['image']; ?>">
  1. 将您升级到mysqli,并向您展示如何准备和执行语句
  2. 如果图像不存在,则发送404未找到状态,并且脚本终止。否则图像为base64_decode'd并输出到浏览器

$db = new mysqli( 'localhost' , 'un' , 'pw', 'datab' );
$userId = intval( $_GET['eid'] ); //convert it to an int.
$stmt = $db->prepare( 'SELECT image FROM event WHERE eid=? LIMIT 1' ); //prepare the statement
$stmt->bind_param( 'i',$userId ); //bind our parameter to the statement
$stmt->execute(); //execute statement
$stmt->bind_result( $img ); //were selecting 1 cell (1 column of 1 row), so we can just bind the result to a single var with this line.
$stmt->store_result(); //store our result, so we can see how many rows it returned.
if($stmt->num_rows !== 1){
    http_response_code( 404 ); //image doesnt exist; send 404 status and die.
    die;
}else{
    $stmt->fetch(); //fetch the result of the statement. this populates `$img` for us
    $stmt->close(); //close the prepared statement. 
    header( 'Content-Type: image/png' ); 
    echo base64_decode( $img ); //base64 decode image and echo it.
}