petercour
Posted on July 6, 2019
What is webp? WebP is Google’s alternative smaller image format to that of JPEGs or PNGs.
You can batch convert image files with Python. One of the newer image formats is webp. WebP is an image format employing both lossy and lossless compression.
In theory this image format is smaller than others. You can convert images in a directory with the python script below
Start
Needs webp tools installed,
sudo apt-get install webp
Then can convert images like this:
#!/usr/bin/python3
import glob
import os
quality = str(100)
imgs = glob.glob("img/*")
for img in imgs:
print(img)
cmd = ("cwebp -q " + quality + " " + img + " -o " + img[:img.index(".")-1] + ".webp")
print(cmd)
os.system(cmd)
Python function
Lets tweak that a little. Turn the whole thing in a function, so you can call it like:
webp("img/*.png",80)
Then the function:
#!/usr/bin/python3
import glob
import os
def webp(directory, quality):
imgs = glob.glob("img/*")
for img in imgs:
print(img)
cmd = ("cwebp -q " + str(quality) + " " + img + " -o " + img[:img.index(".")-1] + ".webp")
print(cmd)
os.system(cmd)
This will convert all the images to webp with 80% quality. When reducing quality the image files will get smaller. You'd think webp is always smaller than png, but that's not the case.
More on webp and python:
Posted on July 6, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 23, 2024
November 5, 2024