PHP - 如何通过浏览器读取图片值并使其可见?

时间:2015-01-15 05:58:27

标签: php zend-framework

我有JPEG / PNG小文件,存储在mysql数据库字段图片中,如下所示:

  $fdata = '';
  if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) {
    $tmpName  = $_FILES['picture']['tmp_name'];  
    $fp      = fopen($tmpName, 'r');
    $fdata = fread($fp, filesize($tmpName));
    $fdata = addslashes($fdata);
    fclose($fp);
    //$sl = "INSERT INTO image (image)VALUES ( '$data')", $connection);
    print "Thank you, your file has been uploaded.";        
  } else {
    print "No image selected/uploaded";        
  }

  // Update the table 
  $this->db->update('users', 
                    array('password' => $_POST['password'], 
                          'picture' => $fdata), 
                    array('username=?' => $ouser )); 

但现在问题是如何将数据库中的“图片字段”值输出到Web浏览器的真实图片中?

编辑1:

简单回声不会在浏览器中呈现图片

enter image description here

编辑2:

enter image description here

  public function pictureshowAction() {  
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender();
    $this->_response->setHeader('Access-Control-Allow-Origin', '*');
    $this->db = Application_Model_Db::db_load();        
    $ouser = $_GET['ousername'];

    $sql = "select *From users where username='{$ouser}' limit 1";
    $result = $this->db->fetchAll($sql);
    if (count($result) > 0 ) {
      $picture  = $result[0]['picture'];     
      //$content = $picture; 
      $content = stripslashes($picture);
    } else {
      $content = '';
    }

    //echo $content;    

    $this->getResponse()
            ->setHeader('Content-Type', 'image/jpg')
            ->setBody($content)
            ->sendResponse();    
    exit;
  }   

1 个答案:

答案 0 :(得分:1)

非常简单,我们说您的内容类型为png,您首先需要向浏览器发送正确的标题

header('Content-type: image/png');

然后只输出你的图片内容

echo $pictureContentFromDatabase;

您的屏幕截图显示的原因是您没有发送正确的内容类型标题,告诉浏览器您的服务器发送的是图像,一旦您修复它就没问题了。并且你没有addslashes输出,这将使图像无用。因此,在没有addslashes

的情况下回复内容