首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中输出图像

在PHP中输出图像
EN

Stack Overflow用户
提问于 2009-12-05 18:42:45
回答 9查看 143.6K关注 0票数 74

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

,它具有mime类型$type

如何将其输出到浏览器?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2009-12-05 18:46:03

代码语言:javascript
复制
$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
票数 148
EN

Stack Overflow用户

发布于 2009-12-05 18:53:42

如果你可以自己配置你的网络服务器,像mod_xsendfile (用于Apache)这样的工具比用PHP读取和打印文件要好得多。您的PHP代码将如下所示:

代码语言:javascript
复制
header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();

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

票数 32
EN

Stack Overflow用户

发布于 2012-02-28 21:38:47

代码语言:javascript
复制
$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

票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1851849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档