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

查看:33
本文介绍了将 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.jpeg2)回显文件内容...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天全站免登陆