'KeyError: 'WEBP' in Pillow 7.2.0 on Ubuntu 20.04 with already installed libwebp-dev

I have managed to build Pillow 7.2.0 using pip like this:

pip install --upgrade Pillow==7.2.0 --global-option="build_ext" --global-option="--enable-webp"

Then in python console I've runned:

In [1]: from PIL import features
In [2]: print (features.check_module('webp'))
True

But my code:

response = requests.get(url)
img = Image.open(BytesIO(response.content))
with open(new_img, "bw+") as f:
    img.save(f, format="WEBP")

fails with:

~/src/myproject/.venv/lib/python3.8/site-packages/PIL/Image.py in save(self, fp, format, **params)
   2116             save_handler = SAVE_ALL[format.upper()]
   2117         else:
-> 2118             save_handler = SAVE[format.upper()]
   2119 
   KeyError: 'WEBP'

Is there anybody out there that has face this issue and can explain me how to fix it. Th anks in advance.



Solution 1:[1]

the workaround is to import the Image from WebPImagePlugin, and not directly from the PIL.

from PIL.WebPImagePlugin import Image

Solution 2:[2]

For docker users

I have added RUN apk add --update --no-cache libwebp-dev into my Dockerfile and it worked. Note that my Pillow version is Pillow==9.0.1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Atul Arvind
Solution 2 adnan kaya