How to change image format to a webp using python ?

Published: December 12, 2022

Updated: December 14, 2022

Tags: Python; Webp;

DMCA.com Protection Status

Webp is a image format developed by google for web site (see An image format for the Web and WebP articles)

To convert an image to webp using python there are multiple solution:

Using Pillow module

A first solution is to use a recent version of Pillow that support webp. To install Pillow:

pip install --upgrade pip

then enter

pip install Pillow

Now using python:

from PIL import Image

Open an existing image:

image = Image.open('example.png')

and convert it to webp:

image.save('example.webp', format="webp")

Convert an ensemble of images located in a directory to webp

Get a list of all images under a given directory

import glob

path_to_src = '/Users/Student/Desktop/Images/src'

images = glob.glob('{}/*'.format(path_to_src))

Now let's save all new images in '/Users/Student/Desktop/Images/webp' directory:

for image in images:
    new_image_path = image.split('.')[0]+'.webp'
    new_image_path = new_image_path.replace('src','webp')
    image_obj = Image.open(image)  
    image_obj.save(new_image_path, format="webp")  webp

Using Webp libraries directly

On Ubuntu I got the following error message:

File "/home/daidalos/anaconda3/lib/python3.7/site-packages/PIL/Image.py", line 2073, in save
save_handler = SAVE[format.upper()]
KeyError: 'WEBP'

So I tried an alternative solution:

Example on Ubuntu

sudo apt install webp

then to convert an image to webp a solution is to do

cwebp example.png -o example.webp

Using python

import os

cmd = 'cwebp {} -o {}'.format('example.png','example.webp')
os.system(cmd)

On multiple images:

import glob
import os

path_to_src = '/Users/Student/Desktop/Images/src'

images = glob.glob('{}/*'.format(path_to_src))

for image in images:
    new_image_path = image.split('.')[0]+'.webp'
    new_image_path = new_image_path.replace('src','webp')
    cmd = 'cwebp {} -o {}'.format(image,new_image_path)
    os.system(cmd)

Example on Macos

On Macos, to install webp we can use brew

brew install webp

then just the same thing that above.