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.
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.
You can check your python pillow version and try the latest one.
As to pillow manul: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#webp
Notice:
Support for animated WebP files will only be enabled if the system WebP library is v0.5.0 or later. You can check webp animation support at runtime by calling features.check(“webp_anim”).
Do you have any solution to convert webp animated images to mp4/webm video?
You can convert webp to other format images, such as png.Then convert these images to video using python MoviePy.
Here is an example tutorial:
https://www.tutorialexample.com/python-create-gif-with-images-using-moviepy-a-complete-guide-python-tutorial/
this tutorial tells you how to create a gif using images using moviepy, you also can create video using it.