2015-05-24 97 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编码还是按原样存储? –