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

Rad*_*ity 0 html php image

我在目录中有一张图片,可以这样说:test.jpg

在此目录中,我还有2个其他PHP文件:new.phpload.php

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

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

我曾试着拨打图像中的img标签,但它无法正确加载,当我插入new.phpimg标签。

<img src="test.jpg">
Run Code Online (Sandbox Code Playgroud)

如果您知道我的意思,那怎么可能使php作为图像工作呢?

t3c*_*guy 6

使用:

header('Content-Type: image/jpeg');
readfile('path/to/image/screenshot.jpg');
Run Code Online (Sandbox Code Playgroud)

其他变体:

@readfile('path/to/image/screenshot.jpg');
Run Code Online (Sandbox Code Playgroud)

如果文件不存在,将不会有任何错误。

readfile('path/to/image/screenshot.jpg') or die('Image file not found');
Run Code Online (Sandbox Code Playgroud)

如果文件不存在,将使用预定义的错误消息终止脚本。

@hd建议的最有用的替代方法:

$file = 'path/to/image/screenshot.jpg';
readfile(file_exists($file) ? $file : 'path/to/image/image_not_found.jpg');
Run Code Online (Sandbox Code Playgroud)

将选择哪个,$file或者如果不存在,则默认image_not_found.jpg

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

注意:另一个答案与这个答案的功能非常相似,但是这个答案不占用内存,通常比另一个答案更快,更灵活。

  • 我在想`$ imagePath = file_exists('path / to / image / screenshot.jpg')吗?'path / to / image / screenshot.jpg':'path / to / image / image_not_found.jpg';`。这样,它将渲染图像,而不显示[损坏的图像链接](http://www.underconsideration.com/brandnew/archives/google_broken_image_00_a_logo.gif) (2认同)