从MySQL服务器解码Base64映像

时间:2015-05-24 23:00:25

标签: php mysql encoding base64

我通过使用Base64对图像进行编码,将我的图像存储为在线MySQL数据库中的BLOB。我没有保存问题。但我无法从服务器检索图像。他们似乎被打破了。我相信这种情况正在发生,因为它没有被解码。

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

<?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']; 
?>

2 个答案:

答案 0 :(得分:0)

首先,请注意mysql语法已过时且完全弃用!请改用mysqli或PDO!

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

    $id = $_POST['id'];

    $result=$ conn->query($sql);
    while($row = $result->fetch_assoc()) {

        if ($row['id'] == $id) {

            $selected = 'selected="selected"';
        }
        else {
            $selected = '';
        }   

        echo '<option value="'.$row['id'].'" '. $selected . '>"'

            . $row['date'].' The Time' 
            . $row['time'].'</option>';
    }

答案 1 :(得分:0)

  1. 升级到mysqli并向您展示如何准备语句并执行它。 (完全披露,我没有在很长一段时间内编写mysqli代码所以它可能是错的)
  2. 如果图像不存在,则发送404未找到状态并且脚本死亡。否则图片为base64_decode&#39; d并输出到浏览器。
  3. $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.
    }