Introducing WebP extension for Middleman

I have been experimenting with Middleman static site generator by runnning my Finnish hobby blog with it. Lately I stumbled upon WebP image format and because Middleman is quite delightfull to extend with own custom plugins, I wrote WebP converter extension to optimize site performance and bandwidth.

Middleman build with WebP conversion

Why should I use WebP images?

WebP is new image format developed by Google supporting both lossless and lossy compression methods. Lossless WebP is about 26% smaller than PNG and lossy version packs 25-34% tighter than equivalent JPEG.

Based on Mozilla’s enthusiasm on mozjpeg project, I think that WebP won’t completely replace other web image formats like jpeg and png, but that won’t actually matter. Browsers that support WebP will include image/webp in Accept request header when requesting images. It means that regular jpeg and png files could be used while eg. htaccess configuration ensures that clients who support WebP will receive it.

It’s good idea to have WebP conversion to complement other image optimization techniques and lower bandwidth required to host sites, because browser’s supporting WebP had about 40% share at the time this post was published.

Using Middleman::WebP extension

Middleman::WebP extension converts all image files found during build. If for some reason converted files are larger than original, the webp version will be rejected from the build.

Extension’s source is hosted at Github and the gem is available for installation at Rubygems.org. It depends on cwebp and gif2webp commandline tools, which are probably available in your system’s software repositories. Fedora user’s have it in libwebp-tools rpm, Ubuntu has it in webp package and OS X users are able to install webp package through Homebrew.

Add following to your Middleman site’s Gemfile:

gem "middleman-webp"

Install gem with bundler:

$ bundle

And activate it in your site’s config.rb to enable build time conversion:

activate :webp

Next web server has to be configured to serve WebP alternatives to clients accepting it. I used following htaccess snippet originally published at Vincent Orback’s github repo.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
    RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
</IfModule>

<IfModule mod_headers.c>
    Header append Vary Accept env=REDIRECT_accept
</IfModule>

AddType image/webp .webp

Word about my results

In my experiments I got about 4 MiB savings from WebP while jpeg and png optimizations produced 220 KiB smaller files. That’s quite drastic difference compared to the officially reported 25-34% WebP efficiency and it’s explained by lossy WebP compression that I’m using for all image types at that site because I didn’t notice any visual difference.

comments powered by Disqus