How to create avif files in php?

6.1k Views Asked by At

Does anybody know how to write avif image files in php? For webp files i have the function imagewebp. But avif?

Using PHP Version 7.4, 7.1 and 7.2 on different servers.

thanks a lot

4

There are 4 best solutions below

2
On

Unfortunately, there is no native PHP support (in any PHP version I know of) for the AVIF/AV1 image file formats, at this stage.

PHP normally relies on the GD, the ImageMagick, the GMagick (and Exif) image libraries, so - until these include support for the AVIF/AV1 image file formats, I'm afraid there won't be an easy (and "native") solution for you. There may be some third-party libraries, perhaps written in pure PHP, to support this, however the format is relatively new and not quite yet widely supported, so I believe it will take some time for these to be available, and a pure-PHP library for image processing is likely to be quite inefficient, performance-wise.

That said, I suppose you could consider using a workaround, which is PHP-generating an image in any of the other image formats (say JPEG or PNG), and then using a command-line tool to covert the resulting image file into AVIF/AV1?

See for example https://reposhub.com/rust/image-processing/kornelski-cavif.html

0
On

Good news - the work's been done to support AVIF in libgd, and this work has been propagated into PHP. It should be released in PHP 8.1.

Enjoy!

0
On

EDIT:

It has been implemented in PHP 8.1 https://php.watch/versions/8.1/gd-avif


There is no dedicated function to do that at this moment. GD has implemented AVIF support but is not yet implemented in PHP. They are working on it https://bugs.php.net/bug.php?id=80828 , please vote for it.

Until that function is made, I image there can be other methods to create:

(1) using php exec/shell_exec and an command line app (like imagemagik). untested code:

if (function_exists("exec")) {
  $command = "convert -size 600x600 canvas:white white.avif ";
  exec($command, $output);
  print("<pre>".print_r($output,true)."</pre>"); //debug
} 
else {
  echo "EXEC function is not available. See php.ini disabled_functions.<br />\n";
}

(2) using a php module like Imagik

https://www.php.net/manual/en/book.imagick.php

Verify ImageMagick installation


For both methods you need to make sure you have a recent version of ImageMagik compiled with proper libraries. https://github.com/ImageMagick/ImageMagick/issues/1432

0
On

As Ben Morss mentioned above, it was implemented in PHP 8 >= 8.1.0 via imageavif function.

Example:

$image = imagecreatefromjpeg('yourImage.jpg');
imageavif($image, 'yourImageAsAvif.avif');

See docs.