从mysql blob中检索图像并将其显示在img标记中

时间:2015-11-06 03:58:15

标签: php database image blob

我正在尝试从我的数据库中获取图像并显示uder图像标记,但它显示的图像已损坏。问题出在哪儿?

$query="SELECT  imagetype,Attachments from Events where E_id='$id' ";
 $result = mysqli_query($link,$query);
 // $image = mysql_result($result,0);

 // echo "<img src =".$image."/>";
if ($row = mysqli_fetch_array($result)){
    // echo $row['Attachments'];
  header('content-type: image/jpeg');
  // exit();
  echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Attachments']).'" alt="photo"><br>';}
?>

1 个答案:

答案 0 :(得分:0)

Class image.php

 <?php
        class image extends mysqli {
         public $a = array();

            public function __construct($host, $user,$password,$db_name) {
                parent::mysqli($host, $user,$password,$db_name);
            }
            public function save() {
                $num = count($this->a);
                $i = 0;
                foreach ($this->a as $c) {
                    $ext = explode(".", $c);
                    $this->query("INSERT INTO Events set name='{$c}',Attachments='" . $this->real_escape_string(file_get_contents($c)) . "',imagetype='" . $ext[count($ext) - 1] . "'");
                    $i++;
                } 
                return $i == $num;
            }

            public function select($id) {
                $rs = array();
                $sql = "SELECT * FROM Events WHERE 1";
                if ($id != NULL) {
                    $sql.=' AND E_id=' . $id;
                }
                $query = $this->query($sql);
                if ($query->num_rows) {
                    while ($line = $query->fetch_object()) {
                        $rs[] = $line;
                    }
                }
                return $rs;
            }


        }
        $image_url=array('');//contain array of image url if you would like to save 
        $obj=new image($host, $user,$password,$db_name);
        $obj->a=$image_url;
        $obj->save();
        $row=$obj->select(isset($_GET['id'])?$_GET['id']:1);
        header("Content-type: image/{$row[0]->imagetype}");
        echo $row[0]->image;

show.html

 <html>
    <head></head>
    <body>
        <img src="image.php?id=<?php echo $_GET['id']?>" width="175" height="200" />
    </body>
</html>