Output an Image in PHP

2019-01-01 02:07发布

I have an image $file ( eg ../image.jpg )

which has a mime type $type

How can I output it to the browser?

标签: php image
9条回答
怪性笑人.
2楼-- · 2019-01-01 02:39

If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:

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

mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.

查看更多
梦该遗忘
3楼-- · 2019-01-01 02:43

Try this:

<?php
  header("Content-type: image/jpeg");
  readfile("/path/to/image.jpg");
  exit(0);
?>
查看更多
倾城一夜雪
4楼-- · 2019-01-01 02:44

You can use header to send the right Content-type :

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

And readfile to output the content of the image :

readfile($file);


And maybe (probably not necessary, but, just in case) you'll have to send the Content-Length header too :

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


Note : make sure you don't output anything else than your image data (no white space, for instance), or it will no longer be a valid image.

查看更多
伤终究还是伤i
5楼-- · 2019-01-01 02:48
<?php

header("Content-Type: $type");
readfile($file);

That's the short version. There's a few extra little things you can do to make things nicer, but that'll work for you.

查看更多
只若初见
6楼-- · 2019-01-01 02:49
$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

查看更多
爱死公子算了
7楼-- · 2019-01-01 02:49
header('Content-type: image/jpeg');
readfile($image);
查看更多
登录 后发表回答