如何使用PHP将图像直接加载到页面?

时间:2014-07-23 12:40:58

标签: php html image

我有一个直截了当的形象,让我们说:test.jpg

我在此目录中还有另外两个PHP文件:new.phpload.php

现在,我想要做的是,当人们访问网站new.php时,他们应该看到test.jpg图片。

然而!如果我将new.php放入<img>标记,我还需要它,它还应该正确显示图像。

我尝试在img代码中调用图片,但是当我将new.php插入img代码时,它无法正确加载。

<img src="test.jpg">

如果你知道我的意思,那怎么可能让php作为一个图像工作?

2 个答案:

答案 0 :(得分:4)

使用:

header('Content-Type: image/jpeg');
readfile('path/to/image/screenshot.jpg');

其他变种:

@readfile('path/to/image/screenshot.jpg');
如果文件不存在,

将不会有任何错误。

readfile('path/to/image/screenshot.jpg') or die('Image file not found');
如果文件不存在,

将使用预定义的错误消息终止您的脚本。

@hd:

建议的最有用的替代方案
$file = 'path/to/image/screenshot.jpg';
readfile(file_exists($file) ? $file : 'path/to/image/image_not_found.jpg');

选择$file或如果不存在,则默认为image_not_found.jpg

您可能需要更改其他图像类型的header()中的mime类型。

注意:另一个答案与此功能非常相似,但是这个答案不使用内存,一般来说比其他答案更快,更灵活。

答案 1 :(得分:1)

试试这个:

<强> new.php

header("Content-Type: image/jpeg");

$im = imagecreatefromjpeg("test.jpg");

imagejpeg($im);
imagedestroy($im);

并像这样使用

<img src="new.php"/>