Convert images to webP using Pillow
Asked Answered
E

2

27

I'm trying to convert .jpg images to webp format using PIL.

I'm using the this code:

from PIL import Image
import glob, os

for infile in glob.glob("*.jpg"):
    file, ext = os.path.splitext(infile)
    im = Image.open(infile).convert("RGB")
    im.save(file + ".webp", "WEBP")

But I get the following error on running it:

Traceback (most recent call last):
  File "webp.py", line 7, in <module>
    im.save(file + ".webp", "WEBP")
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 1444, in save
    save_handler = SAVE[format.upper()] # unknown format
KeyError: 'WEBP'

Kindly help me fixing it. I have installed libwebp-dev.

>>> import PIL
>>> dir(PIL)
['PILLOW_VERSION', 'VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '_plugins']
>>> PIL.PILLOW_VERSION
'2.2.1'
>>> PIL.VERSION
'1.1.7'
Eliathas answered 8/11, 2013 at 13:49 Comment(2)
What version of Pillow are you using?Springtail
@SamMussmann I have updated the question with required info.Eliathas
D
47

Make sure to install WEBP dev library for your OS. For Debian/Ubuntu it's libwebp-dev. You may need reinstall Pillow as well. In the output of Pillow install log you should see:

--- WEBP support available
Damien answered 8/11, 2013 at 14:19 Comment(1)
The solution had worked for me, but I forgot to accept the answer. Reinstalling Pillow after installing WEBP library was the key.Eliathas
M
0

You can use your same code with only one changes. You are mentioned format as "WEBP "in capital letters. Just change "webp" (lowercase) as shown here . Your code

from PIL import Image
import glob, os

for infile in glob.glob("*.jpg"):
    file, ext = os.path.splitext(infile)
    print(file)
    im = Image.open(infile).convert("RGB")
    im.save(file + ".webp", "webp")

Formatting reference is given below please check it.

References

Note - We are unable to use Broken or corrupted images. In these formats (.png,.jpg,.jpeg). It will throws error. you can handle by adding below code for broken images.

from PIL import Image,ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

Also, i checked the above code, works well Windows and Ubuntu OS (Linux)

Tested Code

from PIL import Image,ImageFile
import glob, os
ImageFile.LOAD_TRUNCATED_IMAGES = True

for infile in glob.glob("images/*.jpg"):
    file, ext = os.path.splitext(infile)
    print(file)
    im = Image.open(infile).convert("RGB")
    im.save(file + ".webp", "webp")

output

Muzz answered 13/3 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.