[英]PHP, display image with Header()
我正在顯示來自我的網絡根目錄之外的圖像,如下所示:
header('Content-type:image/png');
readfile($fullpath);
content-type: image/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;
case "svg": $ctype="image/svg+xml"; break;
default:
}
header('Content-type: ' . $ctype);
(注意:JPG 文件的正確內容類型是image/jpeg
)
有更好的理由來確定圖像的類型。 使用exif_imagetype
如果您使用此功能,您可以告訴圖像的真實擴展名。
與此功能文件名的擴展名完全無關,這很好。
function setHeaderContentType(string $filePath): void
{
$numberToContentTypeMap = [
'1' => 'image/gif',
'2' => 'image/jpeg',
'3' => 'image/png',
'6' => 'image/bmp',
'17' => 'image/ico'
];
$contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;
if ($contentType === null) {
throw new Exception('Unable to determine content type of file.');
}
header("Content-type: $contentType");
}
您可以從鏈接添加更多類型。
希望能幫助到你。
瀏覽器根據接收到的數據做出最佳猜測。 這適用於標記(網站經常出錯)和其他媒體內容。 無論被告知的 MIME 內容類型如何,接收文件的程序通常可以確定它接收到的內容。
然而,這不是你應該依賴的東西。 建議您始終使用正確的 MIME 內容。
瀏覽器通常可以通過嗅探圖像的元信息來判斷圖像類型。 此外,該標題中應該有一個空格:
header('Content-type: image/png');
盡管名稱很奇怪,但您可以使用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
)
如果您知道文件名,但不知道文件擴展名,則可以使用此功能:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.