PHP,显示带有标题的图像()
我正在显示web根目录外部的图像,如下所示:PHP,显示带有标题的图像(),php,header,Php,Header,我正在显示web根目录外部的图像,如下所示: header('Content-type:image/png'); readfile($fullpath); 内容类型:image/png让我感到困惑 其他人帮我编写了这段代码,但我注意到并非所有图像都是PNG。许多是jpg或gif。 但它们仍然成功地显示出来 有人知道为什么吗?浏览器通常可以通过嗅出图像的元信息来判断图像类型。此外,该标题中应该有一个空格: header('Content-type: image/png'); 浏览器根据收到的数
header('Content-type:image/png');
readfile($fullpath);
内容类型:image/png让我感到困惑
其他人帮我编写了这段代码,但我注意到并非所有图像都是PNG。许多是jpg或gif。但它们仍然成功地显示出来
有人知道为什么吗?浏览器通常可以通过嗅出图像的元信息来判断图像类型。此外,该标题中应该有一个空格:
header('Content-type: image/png');
浏览器根据收到的数据进行最佳猜测。这适用于标记(网站经常出错)和其他媒体内容。接收文件的程序通常可以计算出它接收到的内容,而不考虑它被告知的MIME内容类型
然而,这不是你应该依赖的东西。建议您始终使用正确的MIME内容。最好的解决方案是读取该文件,然后确定它是哪种类型的图像并发送相应的头文件
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpeg"; break;
case "svg": $ctype="image/svg+xml"; break;
default:
}
header('Content-type: ' . $ctype);
(注意:JPG文件的正确内容类型是)确定图像类型有更好的理由。与 如果你使用这个函数,你可以告诉图像的真正扩展 对于这个函数,文件名的扩展名是完全不相关的,这很好 您可以从中添加更多类型
希望有帮助。如果您知道文件名,但不知道文件扩展名,则可以使用此功能:
public function showImage($name)
{
$types = [
'gif'=> 'image/gif',
'png'=> 'image/png',
'jpeg'=> 'image/jpeg',
'jpg'=> 'image/jpeg',
];
$root_path = '/var/www/my_app'; //use your framework to get this properly ..
foreach($types as $type=>$meta){
if(file_exists($root_path .'/uploads/'.$name .'.'. $type)){
header('Content-type: ' . $meta);
readfile($root_path .'/uploads/'.$name .'.'. $type);
return;
}
}
}
注意:JPG文件的正确内容类型是。尽管名称奇怪,但您可以使用该函数。这还将为您提供mime信息:
Array
(
[0] => 295 // width
[1] => 295 // height
[2] => 3 // http://php.net/manual/en/image.constants.php
[3] => width="295" height="295" // width and height as attr's
[bits] => 8
[mime] => image/png
)
我很欣赏抓取扩展的示例代码。明确无疑是最佳实践。您可以简单地使用pathinfo($filename,pathinfo_扩展名),而不是使用substr和strrchr。它更容易阅读。这假设图像文件具有正确的扩展名。另一方面,我发现指定“image/jpeg”可以在任何当前浏览器上显示任何图像类型。但我还没有尝试过图像下载。对于svg,添加以下行:$ctype=“image/svg+xml”;中断代码>。
Array
(
[0] => 295 // width
[1] => 295 // height
[2] => 3 // http://php.net/manual/en/image.constants.php
[3] => width="295" height="295" // width and height as attr's
[bits] => 8
[mime] => image/png
)