将PHP页面作为图像返回 [英] Return a PHP page as an image

查看:168
本文介绍了将PHP页面作为图像返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取图像文件(确切地说是.jpeg),然后将其回显回页面输出,但是显示图像...

I am trying to read a image file (.jpeg to be exact), and 'echo' it back to the page output, but have is display an image...

我的index.php有一个像这样的图像链接:

my index.php has an image link like this:

<img src='test.php?image=1234.jpeg' />

我的php脚本基本上是这样的:

and my php script does basically this:

1)读取1234.jpeg
2)echo文件内容...
3)我有一种感觉我需要用mime类型返回输出,但这是我迷路的地方

1) read 1234.jpeg 2) echo file contents... 3) I have a feeling I need to return the output back with a mime-type, but this is where I get lost

一旦我想到这一点,我将一起删除文件名输入并将其替换为图像ID。

Once I figure this out, I will be removing the file name input all together and replace it with an image id.

如果我不清楚,或者您需要更多信息,请回复。

If I am unclear, or you need more information, please reply.

推荐答案

PHP手册此示例

<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;
?>

重点是您必须发送Content-Type标头。此外,在<?php ...?> 标记之前或之后,您必须小心不要在文件中包含任何额外的空格(如换行符)。

The important points is that you must send a Content-Type header. Also, you must be careful not include any extra white space (like newlines) in your file before or after the <?php ... ?> tags.

根据评论中的建议,您可以通过省略?> 标签:

As suggested in the comments, you can avoid the danger of extra white space at the end of your script by omitting the ?> tag:

<?php
$name = './img/ok.png';
$fp = fopen($name, 'rb');

header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

fpassthru($fp);

您仍然需要小心避免脚本顶部的空格。一个特别棘手的白色空间形式是 UTF-8 BOM 。为避免这种情况,请确保将脚本保存为ANSI(记事本)或ASCII或无签名的UTF-8(Emacs)或类似内容。

You still need to carefully avoid white space at the top of the script. One particularly tricky form of white space is a UTF-8 BOM. To avoid that, make sure to save your script as "ANSI" (Notepad) or "ASCII" or "UTF-8 without signature" (Emacs) or similar.

这篇关于将PHP页面作为图像返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆