Best Practice to Python Convert PNG to WebP with Pillow – Python Pillow Tutorial

By | August 30, 2020

WebP format is a good choice for displaying images on website. WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25-34% smaller than comparable JPEG images at equivalent SSIM quality index. In this tutorial, we will introduce how to convert png to webp image with python, you also can convert other formats to webp by following our tutorial.

Prerequisite

from PIL import Image

Set a png image

image_old = 'e:\\1.png'
image_new = 'e:\\1.webp'

Convert png to webp format

im = Image.open(image_old)
im.save(image_new, format = "WebP", lossless = True)

Notice: you must set lossless = True, otherwise the size of webp may be bigger than png.

Compare size

1.png  92.0 KB

1.webp 36.0 KB

Saving about 60% disk space.

4 thoughts on “Best Practice to Python Convert PNG to WebP with Pillow – Python Pillow Tutorial

  1. Francisco Javier

    Well, I tried this, but I get this error

    File “/usr/local/lib/python3.6/site-packages/PIL/Image.py”, line 2091, in save
    save_handler = SAVE[format.upper()]
    KeyError: ‘WEBP’

    I guess i must install some library to achieve the conversion.

Leave a Reply