Mic*_*ICE 61 php image-processing http-headers mime-types
我试图读取一个图像文件(确切地说是.jpeg),然后"回显"它回到页面输出,但是显示图像...
我的index.php有一个像这样的图像链接:
<img src='test.php?image=1234.jpeg' />
Run Code Online (Sandbox Code Playgroud)
我的PHP脚本基本上这样做:
1)读取1234.jpeg 2)echo文件内容... 3)我有一种感觉我需要用mime类型返回输出,但这是我迷路的地方
一旦我搞清楚了,我将一起删除文件名输入并将其替换为图像ID.
如果我不清楚,或者您需要更多信息,请回复.
Mar*_*ler 106
PHP手册有这个例子:
<?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;
?>
Run Code Online (Sandbox Code Playgroud)
重要的一点是,您必须发送Content-Type标头.此外,您必须注意不要在<?php ... ?>标记之前或之后在文件中包含任何额外的空格(如换行符).
正如评论中所建议的那样,您可以通过省略?>标记来避免脚本末尾出现额外空格的危险:
<?php
$name = './img/ok.png';
$fp = fopen($name, 'rb');
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
fpassthru($fp);
Run Code Online (Sandbox Code Playgroud)
您仍然需要小心避免脚本顶部的空白区域.一个特别棘手的白色空间形式是UTF-8 BOM.为避免这种情况,请确保将脚本保存为"ANSI"(记事本)或"ASCII"或"无签名的UTF-8"(Emacs)或类似内容.
ban*_*ing 21
readfile()通常也用于执行此任务,并且似乎是比使用更好的解决方案fpassthru().
它适用于我,根据文档,它不会出现任何内存问题.
这是我在行动中的例子:
$file_out = "myDirectory/myImage.gif"; // The image to return
if (file_exists($file_out)) {
//Set the content-type header as appropriate
$image_info = getimagesize($file_out);
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
header("Content-Type: image/jpeg");
break;
case IMAGETYPE_GIF:
header("Content-Type: image/gif");
break;
case IMAGETYPE_PNG:
header("Content-Type: image/png");
break;
default:
header($_SERVER["SERVER_PROTOCOL"] . " 500 Internal Server Error");
break;
}
// Set the content-length header
header('Content-Length: ' . filesize($file_out));
// Write the image bytes to the client
readfile($file_out);
}
else { // Image file not found
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85394 次 |
| 最近记录: |