I was thinking about using webp images to reduce page size and the amount of data transmitted when viewing the blog so started looking at conversion apps for my phone. While webp support exists in most modern browsers now it may still be the case that people are using one that still doesn't support them, especially older versions, so I couldn't just upload webp files.
The obvious answer was to automatically convert images when uploaded using the PHP function imagewebp
. Only one problem: how to handle the image fallback as I use Markdown to write posts?
The solution was a custom content filter using the markup similar to how an image is defined in Markdown and inline with the existing filters. I also added the ability to include optional attributes of class and alt text. 1 An image would, therefore, be added to a post as follows:
The path_to_img is the original uploaded file. If that is a png or jpg it gets converted to webp and a <picture>
tag built with the relevant images and attributes added.
The above image was uploaded as a png but the webp version will be displayed for those browsers that support it.
-
which is also used as the image title attribute ↩