代码之家  ›  专栏  ›  技术社区  ›  steven

用PHP输出图像

  •  62
  • steven  · 技术社区  · 16 年前

    我有个图像 $file (如 ../image.jpg )

    它有一个mime类型 $type

    如何将其输出到浏览器?

    11 回复  |  直到 7 年前
        1
  •  120
  •   Emre Yazici    16 年前
    $file = '../image.jpg';
    $type = 'image/jpeg';
    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    
        2
  •  29
  •   Benjamin Wohlwend    16 年前

    如果您有权自己配置Web服务器,那么 mod_xsendfile (对于Apache)比用PHP读取和打印文件要好得多。您的PHP代码如下所示:

    header("Content-type: $type");
    header("X-Sendfile: $file"); # make sure $file is the full path, not relative
    exit();
    

    mod x sendfile获取x-sendfile头并将文件发送到浏览器本身。这会对性能产生真正的影响,特别是对于大文件。大多数建议的解决方案将整个文件读取到内存中,然后打印出来。对于一个20kbyte的图像文件来说,这是可以的,但是如果你有一个200mbyte的TIFF文件,你肯定会遇到问题。

        3
  •  22
  •   Mike    14 年前
    $file = '../image.jpg';
    
    if (file_exists($file))
    {
        $size = getimagesize($file);
    
        $fp = fopen($file, 'rb');
    
        if ($size and $fp)
        {
            // Optional never cache
        //  header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
        //  header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        //  header('Pragma: no-cache');
    
            // Optional cache if not changed
        //  header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
    
            // Optional send not modified
        //  if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) and 
        //      filemtime($file) == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
        //  {
        //      header('HTTP/1.1 304 Not Modified');
        //  }
    
            header('Content-Type: '.$size['mime']);
            header('Content-Length: '.filesize($file));
    
            fpassthru($fp);
    
            exit;
        }
    }
    

    http://php.net/manual/en/function.fpassthru.php

        4
  •  3
  •   code_burgar    16 年前
    header('Content-type: image/jpeg');
    readfile($image);
    
        5
  •  3
  •   Carlos Lima    16 年前

    试试这个:

    <?php
      header("Content-type: image/jpeg");
      readfile("/path/to/image.jpg");
      exit(0);
    ?>
    
        6
  •  0
  •   Matthew Scharley    16 年前
    <?php
    
    header("Content-Type: $type");
    readfile($file);
    

    这是简短的版本。有一些额外的小事情你可以做,使事情更好,但这将为你工作。

        7
  •  0
  •   Pascal MARTIN    16 年前

    你可以使用 header 要发送正确的内容类型:

    header('Content-Type: ' . $type);
    

    readfile 要输出图像的内容:

    readfile($file);
    


    也许 (可能不需要,但以防万一) 您还必须发送内容长度标题:

    header('Content-Length: ' . filesize($file));
    


    注意:请确保不输出图像数据以外的任何内容 (例如,没有空白) ,否则它将不再是有效的图像。

        8
  •  0
  •   Fabien Sa Shami    10 年前

    你可以使用 finfo (php 5.3+)获取正确的mime类型。

    $filePath = 'YOUR_FILE.XYZ';
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $contentType = finfo_file($finfo, $filePath);
    finfo_close($finfo);
    
    header('Content-Type: ' . $contentType);
    readfile($filePath);
    

    聚苯乙烯 :您不必指定 Content-Length 阿帕奇会帮你的。

        9
  •  0
  •   Tomo Hadi Sutomo    9 年前
        $file = '../image.jpg';
        $type = 'image/jpeg';
        header('Content-Type:'.$type);
        header('Content-Length: ' . filesize($file));
        $img = file_get_contents($file);
        echo $img;
    

    这对我有用!我在代码点火器上测试过。如果我使用readfile,图像将不会显示。有时只显示JPG,有时只显示大文件。但当我把它改成“文件-获取-内容”后,我就得到了味道,并且开始工作了!你说什么? 这是截图: Screenshot of "secure image" from database

        10
  •  0
  •   Hans    7 年前

    对于下一个遇到这个问题的男人或女孩,以下是对我有用的:

    ob_start();
    header('Content-Type: '.$mimetype);
    ob_end_clean();
    $fp = fopen($fullyQualifiedFilepath, 'rb');
    fpassthru($fp);
    exit;
    

    你需要所有这些,只有那些。如果您的mime type不同,请查看php的mime-content-type($filepath)

        11
  •  0
  •   ashleedawg    7 年前

    (扩展到 accepted answer ……)

    我需要:

    1. 日志视图 A的 jpg 形象 有生气的 gif , 而且,
    2. 确保图像 从不缓存 (因此每个视图都会被记录) 而且,
    3. 保持 这个 原始文件扩展名 .

    我通过创建一个 “次级” .htaccess 文件 在图像所在的子文件夹中。
    文件只包含一行:

    AddHandler application/x-httpd-lsphp .jpg .jpeg .gif
    

    在同一个文件夹中,我放置了两个“原始”图像文件(我们将称之为 orig.jpg orig.gif 以及下面的[简化]脚本的两个变体(另存为 myimage.jpg myimage.gif )

    <?php 
      error_reporting(0); //hide errors (displaying one would break the image)
    
      //get user IP and the pseudo-image's URL
      if(isset($_SERVER['REMOTE_ADDR'])) {$ip =$_SERVER['REMOTE_ADDR'];}else{$ip= '(unknown)';}
      if(isset($_SERVER['REQUEST_URI'])) {$url=$_SERVER['REQUEST_URI'];}else{$url='(unknown)';}
    
      //log the visit
      require_once('connect.php');            //file with db connection info
      $conn = new mysqli($servername, $username, $password, $dbname);
      if (!$conn->connect_error) {         //if connected then save mySQL record
       $conn->query("INSERT INTO imageclicks (image, ip) VALUES ('$url', '$ip');");
         $conn->close();  //(datetime is auto-added to table with default of 'now')
      } 
    
      //display the image
      $imgfile='orig.jpg';                             // or 'orig.gif'
      header('Content-Type: image/jpeg');              // or 'image/gif'
      header('Content-Length: '.filesize($imgfile));
      header('Cache-Control: no-cache');
      readfile($imgfile);
    ?>
    

    图像渲染(或动画)正常,可以以任何正常方式调用图像(如 <img> 标记),并将保存访问IP的记录,但用户不可见。

    推荐文章