以图像形式返回 PHP 页面
我正在尝试读取图像文件(确切地说是 .jpeg),并将其“回显”回页面输出,但显示图像...
我的 index.php 有一个像这样的图像链接:
<img src='test.php?image=1234.jpeg' />
和我的 php脚本基本上执行以下操作:
1)读取1234.jpeg 2)回显文件内容... 3)我有一种感觉,我需要用 mime 类型返回输出,但这就是我迷失的地方,
一旦我弄清楚了这一点,我将删除所有输入的文件名并用图像 ID 替换它。
如果我不清楚,或者您需要更多信息,请回复。
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...
my index.php has an image link like this:
<img src='test.php?image=1234.jpeg' />
and my php script does basically this:
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
PHP手册有这个例子:
重要的一点是你必须发送一个内容- 键入标题。 另外,您必须小心,不要在文件中的
标记之前或之后包含任何额外的空格(例如换行符)。
正如评论中所建议的,您可以通过省略
?>
标记来避免脚本末尾出现额外空格的危险:您仍然需要小心避免脚本顶部出现空格。 一种特别棘手的空白形式是 UTF-8 BOM。 为了避免这种情况,请确保将脚本保存为“ANSI”(记事本)或“ASCII”或“无签名的UTF-8”(Emacs)或类似格式。
The PHP Manual has this example:
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: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.
我觉得我们可以通过从 $image_info 获取 mime 类型来使此代码更容易一些:
使用此解决方案可以处理任何类型的图像,但这只是另一种选择。 感谢 ban-geoengineering 的贡献。
I feel like we can make this code a little bit easier by just getting the mime type from $image_info:
With this solution any type of image can be processed but it is just another option. Thanks ban-geoengineering for your contribution.
我在没有 Content-Length 的情况下工作。 也许是远程图像文件工作的原因
I worked without Content-Length . maybe reason work for remote image files
非常非常容易。
Very, very easy.
这应该有效。 它可能会更慢。
This should work. It may be slower.
如果您不从数据库中读取数据,另一个简单的选择(没有更好,只是不同)是使用一个函数来为您输出所有代码......
注意:如果您还希望 php 读取图像尺寸并将其提供给客户端以加快渲染速度,您也可以使用此方法轻松做到这一点。
Another easy Option (not any better, just different) if you aren't reading from a database is to just use a function to output all the code for you...
Note: If you also wanted php to read the image dimensions and give that to the client for faster rendering, you could easily do that too with this method.