AVIF是一种基于AV1视频编码的新图像格式,相对于JPEG,WEBP这类图片格式来说,它的压缩率更高,并且画面细节更好。而最关键的是,它是免费且开源的,没有任何授权费用。
GD 扩展依赖于 libavif 包来提供底层的 AVIF 编解码器。GD 扩展需要 libavif 版本 0.8.2 或更高版本。
Ubuntu/Debian
apt install libavif-dev
RHEL/Fedora
dnf install libavif-devel
安装依赖项后,可以使用 ./configure 脚本中新的 –with-avif 标志在 AVIF 支持下编译 PHP。
./buildconf –force
./configure –enable-gd –with-avif
请注意,上面的 ./configure 命令只是一个示例;对于生产系统,请确保也启用其他扩展。
测试 AVIF 可用性
phpinfo() 和 php -i CLI 命令应该显示 AVIF 图像.
php -i | grep AVIF
AVIF Support => enabled
也可以从 PHP gd_info 函数中检索 GD 功能的列表。
gd_info();
[
“GD Version” => “bundled (2.1.0 compatible)”,
“FreeType Support” => false,
// …
“AVIF Support” => true,
]
此外,还有两个新功能,imagecreatefromavif和imageavif,它们仅在使用AVIF支持编译GD扩展时才可用。
if (function_exists(‘imageavif’)) {
// AVIF support available.
}
将 JPEG 图像转换并保存到 AVIF
$image = imagecreatefromjpeg(‘image.jpeg’);
imageavif($image, ‘image.avif’);
将 AVIF 图像转换并保存到 PNG
$image = imagecreatefromavif(‘image.avif’);
imagepng($image, ‘image.png’);
以多种格式裁剪和保存图像
$image = imagecreatefromjpeg(‘image.jpg’);
$cropped_image = imagecrop($image, [‘x’ => 0, ‘y’ => 0, ‘width’ => 200, ‘height’ => 200]);
imagewebp($cropped_image, ‘cropped.webp’);
imageavif($cropped_image, ‘cropped.avif’);