Notes
Getting started with WebP on Ubuntu
converting images to WebP on Ubuntu with cwebp, batch converting a folder, and serving them with a picture tag fallback
System Administration
2 minutes
1sudo apt update
2sudo apt install webp
1cwebp -q 100 sample_image.png -o sample_image.webp
1# convert all jpeg files in a folder
2for F in *.jpg; do cwebp $F -o `basename ${F%.jpg}`.webp; done
3
4# Convert all files in a directory
5for file in images/*; do cwebp "$file" -o "${file%.*}.webp"; done
using the <picture> tag
Before:
1<img src="flower.jpg" alt="" />
After:
1<!-- order of listing matters in source tag. top will be tried first -->
2<picture>
3 <source type="image/webp" srcset="flower.webp" />
4 <source type="image/jpeg" srcset="flower.jpg" />
5 <!-- img tag should always be included, and it should always be last -->
6 <img src="flower.jpg" alt="" />
7</picture>
key takeaways
- i can automate the process of generating webp version whenever a new image file is uploaded
- i can serve the images using
mod_rewrite, and take care of it on a server level. No need to add<picture>elements inside existing code - going through the sample gallery, PNG files seem to look better after converted to WEBP
- WebP offers both lossless and lossy compression. In lossless compression no data is lost. Lossy compression reduces file size, but at the expense of possibly reducing image quality.
- you can use imagemin-webp as an npm package and integrate it into your bundler (Webpack, Grunt etc.)
- In
<picture>, the browser uses the first listed source that’s in a format it supports. If the browser does not support any of the formats listed in the<source>tags, it falls back to loading the image specified by the<img>tag.