How To Generate AVIF Images In PHP Today
The AVIF image format is a really exciting, it promises much higher compression without any noticeable loss of quality and is supported in most of the major browsers. If you want all the nitty gritty Jake Archibalds wrote an excellent article on the subject. I want to show you know how you can start using AVIF today in PHP!
Compile All The Things!
All image manipulation in PHP is done through extensions, the two main ones are GD and Imagick. For our use case Imagick makes the most sense as the system libraries that the extension hooks into already have support for AVIF, it all just needs configuring.
All that is required is to build ImageMagick v7 and the imagick extension from source making sure that all the required libraries and binaries are available - easier said than done. The libraries specifically required for AVIF are libaom >v2.0.0 and libheif >v1.9.1 but there are also many others that are needed for JPEG, PNG, WEBP etc but all are available through the global repos in any modern Linux based OS.
Standing On The Shoulders Of Giants
While researching this I came across this project. It's a Dockerfile which compiles the latest ImageMagick with support for AVIF. Don't you just love it when the wheel has been invented for you? I guess in this case it is only half a wheel but still!
The other half of this wheel also takes the form of a Dockerfile this is much simpler than the first and follows the standard module build process
So How Do You Actually Use It?
Well if you are using Docker to run your application you can make use of multistep builds and just copy in the module and compiled libraries and binaries like this:
FROM freshleafmedia/imagick-avif as php-imagick
RUN mkdir /libs && ldd /usr/local/bin/magick | grep "=> /" | awk '{print $3}' | xargs -I '{}' cp -v '{}' /libs
FROM myAppBaseContainer
COPY --from=php-imagick /libs /usr/local/lib
COPY --from=php-imagick /usr/local/bin/* /usr/local/bin/
COPY --from=php-imagick /phpmods/modules/imagick.so /usr/lib/php/20190902/
...
If you are running a bare metal server then just run the commands from the Dockerfiles directly on the server, though be aware the Dockerfiles are based on Debian.
You can confirm ImageMagick has AVIF support by running magick -list format
it should output, amongst other things, this:
Format Mode Description
-------------------------------------------------------------------------------
...
AVIF* rw+ AV1 Image File Format (1.9.1)
...
The Ecosystem Adoption Problem
A word of warning: if you plan on encoding AVIF images through a PHP framework be aware that many of them haven't yet added support, even if that support is trivial. I've already opened a PR to intervention/image and once that is merged the same thing for thephpleague/glide