Skip to content

Instantly share code, notes, and snippets.

@dgtlmoon
Created March 16, 2020 09:49
Show Gist options
  • Save dgtlmoon/934452803f0fd9012f9a8476480a4658 to your computer and use it in GitHub Desktop.
Save dgtlmoon/934452803f0fd9012f9a8476480a4658 to your computer and use it in GitHub Desktop.
Snippet convert JPEG/etc to WEBP
#!/usr/bin/python3
def image_to_webp(src, dest):
import webp
import io
from PIL import Image
# @todo Maybe there's a better way to load this as a stream instead of into RAM, tho my images are all small.
with open(src, "rb") as r:
rb = r.read()
o = Image.open(io.BytesIO(rb))
r.close()
pic = webp.WebPPicture.from_pil(o)
config = webp.WebPConfig.new(preset=webp.WebPPreset.PICTURE, quality=80)
buf = pic.encode(config).buffer()
with open(dest, 'wb') as f:
f.write(buf)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment