从mySQL显示时,奇怪的字符而不是图像

时间:2011-06-02 19:05:08

标签: php mysql

我正在尝试从mySQL中显示一个blob图像,而我却变得很怪异。

要插入我使用的数据:

  if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

  // Temporary file name stored on the server
  $tmpName  = $_FILES['image']['tmp_name'];  

  // Read the file 
  $fp      = fopen($tmpName, 'r');
  $data = fread($fp, filesize($tmpName));
  $data = addslashes($data);
  fclose($fp);

// Insert data into mysql
$sql="INSERT INTO $tbl_name( image )VALUES('$data')";
$result=mysql_query($sql);
}

显示:

$tbl_name="table"; // Table name
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);

if (!$result) {
echo "There is nothing";
}

while($rows= mysql_fetch_assoc($result)){

//header('Content-type: image/jpg'); 
 echo $rows['image'];

?>

我该如何解决? 提前谢谢。

2 个答案:

答案 0 :(得分:3)

首先,最佳做法是不在您的数据库中存储图像。将它们存储在一个文件夹中。

其次,您将以ASCII格式查看图像的原始数据。

如果您必须将图像存储在数据库中,要回答您的问题,请创建一个新的php文件。

header('content-type: image/png'); // Use a variable for the image type
// Code here to select a single image from the database.
// Echo the database value.

调用图片
<img src="link_to_php_file.php" alt="" />

答案 1 :(得分:1)

您需要发送图片标题,例如:

header("Content-Type: image/png"); // or image/jpeg or image/gif

请注意,每次只能显示一张图片而不能显示任何其他图像。

如果您想在网页上展示多个图片,只需链接到它们即可:

<img src="getimage.php?id=1234" />
<img src="getimage.php?id=1235" />
<img src="getimage.php?id=1236" />

其中getimage.php包含将发送Content-Type标头并从MySQL获取数据BLOB的代码。

相关问题