首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将PHP页面作为图像返回

将PHP页面作为图像返回
EN

Stack Overflow用户
提问于 2009-05-23 06:10:43
回答 5查看 105.6K关注 0票数 72

我正在尝试读取一个图像文件(准确地说是.jpeg),并将其‘回显’到页面输出,但却显示了一个图像……

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

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

我的php脚本基本上做到了这一点:

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

一旦我弄清楚了这一点,我将删除所有输入的文件名,并将其替换为图像id。

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

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-05-22 22:17:03

PHP手册中有this example

<?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
$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 without signature“(Emacs)或类似文件。

票数 128
EN

Stack Overflow用户

发布于 2013-09-30 23:41:41

这应该是可行的。它可能会更慢。

$img = imagecreatefromjpeg($filename);
header("Content-Type: image/jpg");
imagejpeg($img);
imagedestroy($img);
票数 4
EN

Stack Overflow用户

发布于 2018-03-03 02:31:44

我的工作没有内容长度。也许reason对远程图像文件有效

// open the file in a binary mode
$name = 'https://www.example.com/image_file.jpg';
$fp = fopen($name, 'rb');

// send the right headers
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: January 01, 2013'); // Date in the past
header('Pragma: no-cache');
header("Content-Type: image/jpg");
/* header("Content-Length: " . filesize($name)); */

// dump the picture and stop the script
fpassthru($fp);
exit;
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/900207

复制
相关文章

相似问题

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