从以二进制格式存储的数据库中检索图像


To retrieve the image from the database which is stored in binary format

在这个图像以二进制格式存储在数据库中,我想检索它,它显示为一个空框,我希望图像显示为输出。显示功能可能有错误。以下是代码。。。。

<?php
 ini_set('mysql.connect_timeout',300);
 ini_set('default_socket_timeout',300);
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="image"><br><br>
<input type="submit" name="submit" value="upload">
</form>
<?php
// Create connection
 $conn = mysql_connect('localhost', 'root', '');
// Check connection
if (mysqli_connect_error()) {
 die("Database connection failed: " . mysqli_connect_error());
}
   else
  {
     echo "Connected successfully";
   }
 //data upload
 if( isset($_POST['submit'] ))
{
  if(getimagesize($_FILES['image']['tmp_name'])===FALSE)//to get image size
 {
   echo "upload image";
 }
   else
 {
   $uploads_dir = '/newimages';
   $image= addslashes($_FILES['image']['tmp_name']); 
   $name=addslashes($_FILES['image']['name']);
   $image=file_get_contents($image); 
   $image= base64_encode($image); 
   move_uploaded_file($image, "$uploads_dir/$name");
   saveimage($name,$image);
   displayimage();   //display function is called to display images
  }
 }
 function saveimage($name,$image)
 {
    $conn = mysql_connect('localhost', 'root','');
    mysql_select_db("project",$conn);
    $result = mysql_query("insert into images(name,image) values('$name','$image')");
  }
    //display function
  function displayimage()
  {
    $conn = mysql_connect('localhost', 'root','');
    mysql_select_db("project",$conn);
    $result = mysql_query("select * from images");
    while($row =mysql_fetch_array($result))
    {
       echo'<img height="100" width="100" src="data:image;base64,'.$row[2].'">';  //to display image
     }
   mysql_close($conn);
   }
   ?>
    </body>
    </html>

使用base64_encode获得期望结果

echo'<img height="100" width="100" src="data:image;base64,'.base64_encode($row[2]).'">'; 

如果它不起作用,那么试试这个

创建一个名为show_blob_img.php的文件,并将下面的内容放在中

$conn = mysql_connect('localhost', 'root','');
mysql_select_db("project",$conn);
// Get ID from url I guess your primary key is id if not then change with that
$id = $_GET['id'];
$result = mysql_query("select * from images where id="+$id);
$row =mysql_fetch_array($result);
/*** set the headers and display the image ***/
header("Content-type: image/jpeg");
/*** output the image ***/
echo $row[2];
mysql_close($conn); 

并更改

echo'<img height="100" width="100" src="data:image;base64,'.$row[2].'">';  
//to display image

// I guess your first field is id if not then replace it with proper field
echo'<img src="show_blob_img.php?id="'.$row[0].' height="100" width="100" />'; 
//to display image

注意

您必须创建另一个页面,并将该页面类型设置为image.jpg从而可以显示图像。此页面获取您的图像id,以便您可以数据库中的图像,您需要回显该图像代码。

使用此

while($row =mysql_fetch_array($result))
    {
       echo'<img height="100" width="100" src="../uploads/'.$row['name'].'">';  //to display image
     }