WebP Mime 类型

用于 WebP 图像的内容类型(又名 Mime 类型)是 image/webp,标准文件扩展名是 .webp。

WebP 是一种现代图像格式,可提供优于 png 和 jpg 的压缩,有助于更快地加载网页。

大多数现代浏览器都支持 webp 格式,最近苹果的 Safari 浏览器也开始支持 webp,这发生在 2016 年 9 月 16 日发布的 iOS 14 中。

webp 文件的典型标头响应可能如下所示:

HTTP/1.1 200 OK
content-type: image/webp
content-length: 22454

从 PHP 提供图像/webp 内容类型:

header('content-type: image/webp');
echo $image_data;
exit();

使用图片元素

图片元素允许我们包含多个图像,并让客户端自动选择支持的图像。

在实践中,这看起来像:

<picture>
  <source srcset="/path/to/file/some-file-name.webp" type="image/webp">
  <source srcset="/path/to/file/some-file-name.jpg" type="image/jpeg"> 
  <img src="/path/to/file/some-file-name.jpg" alt="If your browser does not support the picture element.">
</picture>

如果不支持图片元素,将显示 img 元素中包含的图像。

将 webp 转换为 jpg

如果客户端支持 webp 格式,则接受头将包含 image/webp;检查字符串,我们可以使用 strpos(或者 PHP8 中的 str_contains):

if (false == strpos($_SERVER['HTTP_ACCEPT'], 'image/webp')) {
  echo 'image/webp is not supported by your client!';
  exit();
}

当然,这不足以提供替代格式;为此,我们还需要转换图像。

转换图像可以使用 GD 库完成,我们可能需要手动安装它,因为它没有随 PHP 一起提供。

要转换图像,我们可以使用以下代码:

$img = imagecreatefromwebp('/path/to/file/some-file-name.webp');
//Convert the file to jpg with 80% quality
imagejpeg($img, null, 80);
imagedestroy($img);
exit();

以上将在相同的请求 URL 上将文件直接输出到客户端。

这对用户体验不利,因为文件的文件扩展名不正确。
它之所以有效,是因为文件类型是由 MIME 类型决定的,而不是由 URL 中的文件扩展名决定的——它只会让用户感到困惑。

更好的解决方案是保存图像,然后重定向到保存(转换)的版本。

如果我们想要保存它,我们应该更改 imagejpeg 函数的第二个参数:

imagejpeg($img, '/path/to/file/some-file-name.jpg', 80);

然后,如果客户端不支持 webp,我们可以将客户端重定向到新文件:

if (false == strpos($_SERVER['HTTP_ACCEPT'], 'image/webp')) {
  header('Location: https://example.com/images/some-file-name.jpg', false, 307);
}

无论我们使用哪种方法,都不能保证它适用于所有服务。

日期:2020-06-02 22:17:36 来源:oir作者:oir