我有一个直截了当的形象,让我们说:test.jpg
。
我在此目录中还有另外两个PHP文件:new.php
和load.php
现在,我想要做的是,当人们访问网站new.php
时,他们应该看到test.jpg
图片。
然而!如果我将new.php
放入<img>
标记,我还需要它,它还应该正确显示图像。
我尝试在img
代码中调用图片,但是当我将new.php
插入img
代码时,它无法正确加载。
<img src="test.jpg">
如果你知道我的意思,那怎么可能让php作为一个图像工作?
答案 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"/>