我正在尝试读取图像文件(准确地说是.jpeg),并将其“回显”回页面输出,但是却显示了图像…
我的index.php具有这样的图像链接:
<img src='test.php?image=1234.jpeg' />
和我的PHP脚本基本上做到这一点:
1)读取1234.jpeg 2)echo文件内容… 3)我觉得我需要使用mime类型返回输出,但这是我迷路的地方
一旦弄清楚了,我将删除所有输入的文件名,并将其替换为图像ID。
如果我不清楚,或者您需要更多信息,请回复。
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 ... ?>标签之前或之后在文件中包含任何多余的空格(例如换行符)。
<?php ... ?>
如注释中所建议,可以通过省略?>标签来避免脚本末尾出现多余空格的危险:
?>
<?php $name = './img/ok.png'; $fp = fopen($name, 'rb'); header("Content-Type: image/png"); header("Content-Length: " . filesize($name)); fpassthru($fp);
您仍然需要小心避免在脚本顶部使用空格。一种特别棘手的空白形式是UTF-8BOM。为避免这种情况,请确保将脚本另存为“ ANSI”(记事本)或“ ASCII”或“ UTF-8无签名”(Emacs)或类似名称。