Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert images to webP using Pillow

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'
like image 990
Sudipta Avatar asked Nov 08 '13 13:11

Sudipta


People also ask

Does pillow work on PNG?

Pillow builds on this, adding more features and support for Python 3. It supports a range of image file formats such as PNG, JPEG, PPM, GIF, TIFF, and BMP. We'll see how to perform various operations on images such as cropping, resizing, adding text to images, rotating, greyscaling, etc., using this library.

Can PNG convert to WebP?

Convert the PNG files into WEBP files. WEBP is a file type specifically designed to make websites run smoothly and maintain good image quality. You can convert PNG to WEBP in no time at all with file conversion software like WinZip.

Is WebP better than PNG?

Essentially WebP offers the following benefits over PNG. WebP offers 26% smaller file sizes than PNG, while still providing transparency and the same quality. WebP loads faster (due to file size) than PNG images.


1 Answers

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
like image 175
exslim Avatar answered Nov 15 '22 17:11

exslim