已经有一个关于使用客户端检测WebP支持的主题讨论了(链接)。如何使用服务器端检测WebP支持?
accept
标头是否包含 image/webp
。所有支持 WebP 的浏览器都会在其所有请求(包括图像和非图像)的接受字符串中发送此标头。简而言之:if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false ) {
// webp is supported!
}
你可能想使用preg_match
并添加单词边界检查和大小写不敏感性,但在现实世界中这应该是可以的。
"正确"的方法是检查发送的accept
头文件,但Chrome中的一个错误意味着它不会列出image/webp
,即使它支持它。
这是一个相关的论坛帖子:https://groups.google.com/a/webmproject.org/forum/#!topic/webp-discuss/6nYUpcSAORs
其中链接到此bugtracker:https://code.google.com/p/chromium/issues/detail?id=169182,它又链接到这个bugtracker:https://code.google.com/p/chromium/issues/detail?id=267212
最终结果?虽然还没有实现,但很快Google Chrome将明确列出image/webp
作为接受类型,用于图像和非图像请求。因此,您的用于提供HTML的脚本可以检查它。Opera已经将image/webp
作为其标准accept
头文件的一部分发送(无论是否是图像请求)。
所以,你可以这样检查:
if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false || strpos( $_SERVER['HTTP_USER_AGENT'], ' Chrome/' ) !== false ) {
// webp is supported!
}
(你可能想使用 preg_match
代替,并添加单词边界检查和不区分大小写,但在现实世界中这应该是可以的。您可能还想检查至少 Chrome 的版本 6,但几乎没有人使用过时版本,所以没有太多意义)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
- Andreas HeintzeDave的回答很好,但不适用于所有浏览器。我使用以下方法:
function GetBrowserAgentName($user_agent) {
if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
elseif (strpos($user_agent, 'Edge')) return 'Edge';
elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
elseif (strpos($user_agent, 'Safari')) return 'Safari';
elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
return 'Other';
}
所以在检查浏览器之后:
$BrowserAgentName = GetBrowserAgentName($_SERVER['HTTP_USER_AGENT']);
If ($BrowserAgentName == 'Chrome' || $BrowserAgentName =='Opera') {
// webp is supported!
}
这里我只添加了Opera和Chrome,您可以使用更深层次的检测器来检测浏览器版本,并在if{}中添加更多的代理。但是,当浏览器更新以支持image/webp时,您需要更新此代码。
if (strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), "facebook"))
return false;
bool acceptsWebP = Request.AcceptTypes.Contains("image/webp");
string ext = Path.GetExtension(image.ImagePath);
string webP = image.ImagePath.Replace(ext, ".webp");
if (acceptsWebP)
{
<img class="img-fluid lazy" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-src="\Uploads\@webP" alt="@item.ProductName">
}
else
{
<img class="img-fluid lazy" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-src="\Uploads\@image.ImagePath" alt="@item.ProductName">
}
$_SERVER['HTTP_ACCEPT']
中获取它吗? - putvande