Providing WebP and AVIF images instead of JPG

I was interested to read the article linked to in the Kirby Kosmos email newsletter – Looking Forward to (Hopefully) Not Needing Responsive Images One Day | Alex MacArthur

In summary the article says that with AVIF and WebP image formats providing substantially smaller images, there is considerable less need to provide responsive images (the same image at different sizes). And that maybe we only need to provide one image in a modern image format.

I’m looking to explore this idea and asses the file sizes of the different image formats. But how do I write the code to provide AVIF images, that fallback to WebP, that fallback to JPG?

The code below seems to work, and I don’t need to do anything with the config.php file. But it’s rather verbose. I was hoping the code would be short and sweet. Any thoughts or pointers welcomed

<?php
if ($image = $page->hero_image()->toFile()): ?>
	<picture>
		<source
			srcset="<?= $image->thumb(['width' => 2400, 'height' => 1600, 'crop' => 'center', 'quality' => 90, format' => 'avif',])->url() ?>"
			type="image/avif"
		>
		<source
			srcset="<?= $image->thumb(['width' => 2400, 'height' => 1600, 'crop' => 'center', 'quality' => 90, 'format' => 'webp',])->url() ?>"
			type="image/webp"
		>
		<img
			alt="<?= $image->alt() ?>"
			src="<?= $image->thumb(['width' => 2400, 'height' => 1600, 'crop' => 'center', 'quality' => 90, 'format' => 'jpg',])->url() ?>"
			width="2400"
			height="1600"
		>
	</picture>
<?php endif ?>

ChatGPT has simplified and removed some repetition. This appears to work (I need to check avif images will be generated on my server).

In this version, I’ve defined the common thumb options in a variable $thumbOptions to avoid repetition. Then I’m using array merging (+ ) to add the specific format option ('format' => 'avif' or 'format' => 'webp' ) to generate AVIF and WebP thumbs. This makes the code more concise and easier to maintain.

<?php
if ($image = $page->hero_image()->toFile()): ?>
	<picture>
		<?php $thumbOptions = ['width' => 2400, 'height' => 1600, 'crop' => 'center', 'quality' => 90]; ?>
		<source srcset="<?= $image->thumb($thumbOptions + ['format' => 'avif'])->url() ?>" type="image/avif">
		<source srcset="<?= $image->thumb($thumbOptions + ['format' => 'webp'])->url() ?>" type="image/webp">
		<img src="<?= $image->thumb($thumbOptions + ['format' => 'jpg'])->url() ?>" alt="<?= $image->alt() ?>" width="2400" height="1600">
	</picture>
<?php endif ?>

If you are creating similar thumb images often you might consider setting a config preset.

1 Like