2015-05-24 95 views
-1

我通過使用Base64對圖像進行編碼,將圖像作爲BLOB存儲在在線MySQL數據庫中。我沒有保存問題。但我無法從服務器上檢索圖像。它們似乎被打破了。我相信這是因爲它沒有被解碼而發生的。從MySQL服務器解碼Base64圖像

我嘗試手動上傳一些照片到服務器,並且他們被正確檢索,因爲他們沒有編碼。這是我用來檢索圖像的代碼。有人可以告訴我如何解碼圖像?

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

Base64是不加密算法。這是一種編碼。要執行加密,您需要某種默認Base64不存在的密鑰。 –

+0

好吧,我的壞。感謝您指出。無論如何,我怎麼解碼? @ArtjomB。 –

+2

從這裏開始解決真實的問題。如果你不修復它,** SQL注入**會給你造成很多麻煩。 – Darren

回答

0

首先,請注意,mysql語法已過時,完全不推薦!請使用mysqli或PDO!

接着,下面的代碼,你只需要調用圖像在HTML文件中,這樣的:

<img src="data:image/png;base64, <?php echo $photo['image']; ?>"> 
+0

實際上,我想用'server/image.php?eid = 351'來測試它,而不是HTML。所以我想當迴應自己時,圖像應該被解碼 –

0
  1. 升級你的mysqli並告訴你如何準備語句並執行它。 (完全披露,我沒有在很長一段時間寫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. 
} 
+0

謝謝你的答案。順便說一句,回顯圖像的格式是什麼?我得到的圖像將顯示在瀏覽器上,但我的最終目標是讓這個圖像顯示在我的android應用程序。在那裏,我使用HTTP URL連接並將流解碼爲位圖。我想知道你的代碼迴應的流的格式是什麼。 –

+0

存儲值的格式是什麼? .bmp?,.jpg?是以base64編碼還是按原樣存儲? –