GD (php8.5-gd, bundling GD 2.3.3) decodes a file into a GdImage of raw pixels that you edit and re-encode. This Ubuntu 225 build has WebP but not AVIF (gd_info()['AVIF Support'] is false, and imageavif() does not exist). Imagick 623 (github.com/Imagick/imagick (https://github.com/Imagick/imagick 623 ), php8.5-imagick 3.8.0 on ImageMagick 7.1.2 3,122 ) writes AVIF, HEIC and some 200 other formats. The photo is a 2400x1600 JPEG of 1,868,688 bytes (Eli Francis, CC0, via Wikimedia Commons).
<?php
declare(strict_types=1);
$src = imagecreatefromstring(file_get_contents('books.jpg')); // sniffs JPEG, PNG, GIF, WebP
imagejpeg($src, 'books-q80.jpg', 80);
imagepng($src, 'books.png', 9);
imagewebp($src, 'books-q80.webp', 80);
$im = new Imagick('books.jpg'); // GD cannot write AVIF
$im->setImageFormat('avif');
$im->setImageCompressionQuality(50);
$im->writeImage('books-q50.avif');
foreach (['books-q80.jpg', 'books.png', 'books-q80.webp', 'books-q50.avif'] as $f) {
printf("%-15s %9s bytes\n", $f, number_format(filesize($f)));
}books-q80.jpg 272,512 bytes books.png 4,414,705 bytes books-q80.webp 112,878 bytes books-q50.avif 64,826 bytes
WebP is 41% of the JPEG and AVIF 24%; check quality by eye. Encode once, at upload time, which also discards anything hidden in an upload (Single File Uploads). imagedestroy() is deprecated in PHP 8.5; a GdImage is freed like any object.