Notes

Creating and using webp images

Edit on GitHub

Web Development
2 minutes

Usage in HTML

1<!-- For browsers tat support it, just use a .webp image as src -->
2<img src="img/WebPimage.webp" alt="WebP rules." />

Safari, iOS Safari, IE, IE Mobile, Firefox, and Firefox for Android have zero support for webp as of this writing on January 04, 2019.

1<!-- Using webp images with fallback -->
2<picture>
3  <source srcset="img/WebPimage.webp" type="image/webp">
4  <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> 
5  <img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
6</picture>

The browsers that support <picture> will choose the most adequate image to display. The ones that don’t will just show the <img> <src>

The HTML <picture> element contains zero or more <source> elements and one <img> element to provide versions of an image for different display/device scenarios.

<source> works with <picture>, <audio> and <video> and is used when you want to specify the same media content in different formats supported by different browsers

 1<video controls
 2    width="250"
 3    height="200"
 4    muted>
 5    <source src="/media/examples/flower.webm"
 6            type="video/webm">
 7    <source src="/media/examples/flower.mp4"
 8            type="video/mp4">
 9    This browser does not support the HTML5 video element.
10</video>

Converting images to webp on Linux

1# install the tools
2sudo apt install -y webp
3
4# convert all files in a folder from webp to png
5find ./ -name "*.webp" -exec dwebp {} -o {}.png \;
6
7# convert all JPEGs to webp
8find ./ -name "*.jpg" -exec cwebp -q 70 {} -o {}.webp \;
  • For JPEGs, use lossy, for PNGs use lossless
  • -q is for quality factor (0:small..100:big), default=75
  • cwebp is for compressing an image file to a WebP file
  • dwebp is for decompressing a WebP file to an image file
  • vwebp is for decompressing a WebP file and displaying it in a window