我我的網站根目錄外顯示來自圖像,像這樣:PHP,用頭顯示圖像()
header('Content-type:image/png');
readfile($fullpath);
的內容類型:圖像/ PNG是什麼讓我困惑。
其他人幫我用這段代碼,但我注意到並非所有的圖片都是PNG。許多是JPG或GIF。
而且它們仍然顯示成功。
有誰知道爲什麼?
我我的網站根目錄外顯示來自圖像,像這樣:PHP,用頭顯示圖像()
header('Content-type:image/png');
readfile($fullpath);
的內容類型:圖像/ PNG是什麼讓我困惑。
其他人幫我用這段代碼,但我注意到並非所有的圖片都是PNG。許多是JPG或GIF。
而且它們仍然顯示成功。
有誰知道爲什麼?
最好的解決辦法是在文件中讀取,然後決定它是一種形象併發出相應的頭
$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;
default:
}
header('Content-type: ' . $ctype);
(注:正確的內容類型爲JPG文件是image/jpeg
)
瀏覽器通常可以通過嗅探圖像的元信息來判斷圖像類型。此外,該標題中應該有空格:
header('Content-type: image/png');
瀏覽器會根據所收到的數據做出最佳猜測。這適用於標記(哪些網站經常出錯)和其他媒體內容。接收文件的程序通常可以找出它收到的內容,而不管它被告知的MIME內容類型。
但這不是你應該依賴的東西。建議您始終使用正確的MIME內容。
有一個更好的爲什麼確定圖像的類型。與exif_imagetype
如果您使用此功能,您可以告訴圖像的真實擴展名。
這個函數filename的擴展名是完全不相關的,這很好。
function set-header-content-type($file)
{
//Number to Content Type
$ntct = Array("1" => "image/gif",
"2" => "image/jpeg", #Thanks to "Swiss Mister" for noting that 'jpg' mime-type is jpeg.
"3" => "image/png",
"6" => "image/bmp",
"17" => "image/ico");
header('Content-type: ' . $ntct[exif_imagetype($file)]);
}
您可以從the link添加更多的類型。
希望它有幫助。
,如果你知道文件的名稱,但不知道該文件擴展您可以使用此功能:
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文件是image/jpeg
。
雖然奇怪的命名,您可以使用getimagesize()
函數。這也將給你的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
)
我欣賞抓住擴展的示例代碼。具體確定是最佳實踐。 – coffeemonitor 2010-04-14 05:38:18
不客氣! – paullb 2013-08-09 09:40:42
$ ctype應該從getimagesize() – Tobia 2013-11-06 16:19:08