Skip to content

Instantly share code, notes, and snippets.

@vinhdn
Created January 22, 2020 02:37
Show Gist options
  • Save vinhdn/71bb4695971d47826a493cb6bc553877 to your computer and use it in GitHub Desktop.
Save vinhdn/71bb4695971d47826a493cb6bc553877 to your computer and use it in GitHub Desktop.
convertImageToWebp.py
from PIL import Image
from os import rename, listdir
from webptools import webplib as webp
basewidth = 512
path = "webp"
fnames = listdir(path)
for fname in fnames:
if fname.startswith("sk") and fname.endswith(".png") and not fname.endswith("_temp.png"):
im = Image.new("RGBA", (basewidth, basewidth), 0)
file = path + "/" + fname
img = Image.open(file)
wSize = basewidth
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
if hsize > basewidth:
hsize = basewidth
wpercent = (basewidth/float(img.size[1]))
wSize = int((float(img.size[0])*float(wpercent)))
img = img.resize((wSize,hsize),resample = Image.BOX)
im.paste(img, (int((basewidth - wSize)/2.0), int((basewidth - hsize) / 2.0)))
temp = path + "/image_temp.png"
im.save(temp, quality = 100, optimize=True)
print(webp.cwebp(temp,(file).replace(".png", ".webp"),"-q 80"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment