简体   繁体   English

PHP-如何读取图片值并使其可被浏览器查看?

[英]PHP - how do i read the picture value and make it viewable by browser?

I have JPEG/PNG small file which is stored in the mysql database field picture as following: 我有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 )); 

But problem is now how do i output that "picture field" value from the database into real picture for web browsers? 但是现在的问题是,如何将数据库中的“图片字段”值输出到Web浏览器的真实图片中?

EDIT 1: 编辑1:

Simply echo does not render the picture in browser 只是echo不会在浏览器中呈现图片

在此处输入图片说明

EDIT 2: 编辑2:

在此处输入图片说明

  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;
  }   

Very easy, let's say your content type was png you first need to send a proper header to browser 非常简单,假设您的内容类型为png ,则首先需要向浏览器发送适当的标头

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

Then simply output your picture content 然后只需输出图片内容

echo $pictureContentFromDatabase;

What your screenshot shows is caused by the fact that you did not send a proper Content Type header telling the browser what your server is sending is an image, once you fix that it will be fine. 屏幕快照显示的原因是由于您没有发送正确的Content Type标头来告诉浏览器服务器正在发送的内容是图像,因此,一旦修复就可以了。 And you dont have to addslashes for output, that will render the image useless. 而且您不必为输出添加addslashes ,这会使图像无用。 So echo the content without addslashes 因此,回显内容时不要加addslashes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM