用PHP输出图像

ste*_*ven 67 php image

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

有哑剧类型 $type

如何将其输出到浏览器?

Emr*_*ici 130

$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
Run Code Online (Sandbox Code Playgroud)

  • PHP和/或服务器将为您处理内容长度. (15认同)
  • 最好避免使用Content-Length,尤其是如果你在网络服务器上启用了GZip,因为你会告诉浏览器期望更多字节而不是实际到达,并且它会等待超时.如果您有JS等待事件,这可能会产生不良后果. (13认同)
  • 由于某种原因,在尝试通过绝对路径访问图像时,文件大小失败,所以我评论该行和代码工作正常. (2认同)

Ben*_*end 30

如果您可以自己配置Web服务器,那么mod_xsendfile(适用于Apache)等工具比使用PHP读取和打印文件要好得多.您的PHP代码如下所示:

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

mod_xsendfile获取X-Sendfile头并将文件发送到浏览器本身.这可以在性能上产生真正的差异,尤其是对于大文件.大多数建议的解决方案将整个文件读入内存然后将其打印出来.这对于一个20k字节的图像文件来说没问题,但如果你有一个200 MB的TIFF文件,你肯定会遇到问题.


Mik*_*ike 22

$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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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


cod*_*gar 5

header('Content-type: image/jpeg');
readfile($image);
Run Code Online (Sandbox Code Playgroud)