All Articles Kinsa Creative

WebP Images

Creating WebP Images

Creating WebP Images Locally on an Apple computer running MacOS

Create webp images with the webp homebrew package.

Install via homebrew

$ brew install webp

Usage

$ cwebp [options] -q quality input.png -o output.webp 

Dwebp can be used for PNG images

$ dwebp in_file [options] [-o out_file]

Creating WebP Images on the server

Python / Django

In a Python web application, WebP images can be created on the fly using the Python Image Library as demonstrated in this StackOverflow response. On Debian/Ubuntu, the libwebp-dev library must be installed before installing PIL.

WordPress

Use the image_editor_ouptut_format hook to map the mimetypes for jpeg and jpg images to the mimetype for WebP images. Add the following to a theme's functions.php file:

// Convert JPG images to WebP
function map_jpeg_to_webp( $formats ) {
    $formats['image/jpeg'] = 'image/webp';
    $formats['image/jpg'] = 'image/webp';
    return $formats;
}

add_filter( 'image_editor_output_format', 'map_jpeg_to_webp' );

Any JPG image will then have WebP thumbnails generated. If thumbnails need to be manually regenerated after adding this function, the WP CLI provides the media regenerate command to do so:

$ wp media regenerate --image-size=spam_and_eggs

Use a WebP image as a background image with a JPG fallback

Use webp as a background image:

.foo {
    background: image-set(url('../img/foo.webp') type('image/webp'), url('../img/foo.jpg') type('image/jpeg')) no-repeat center center;
}

Place a WebP image in HTML with a JPG fallback

As demonstrated in this Digital Ocean piece, webp images can also be used in a <picture> element alongside legacy formats such as JPG.

The advantage with using the images in the markup is the ability to do things like set the correct fetch priority and/or lazy load them.


    
    Foo

Feedback?

Email us at enquiries@kinsa.cc.