簡體   English   中英

從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,並向您展示如何准備語句並執行它。 (完全公開,我很長時間沒有編寫mysqli代碼,所以可能是錯誤的)
  2. 如果圖像不存在,則發送404找不到狀態,腳本死亡。 否則圖像將被base64_decode並輸出到瀏覽器。

$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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM