Skip to content

Instantly share code, notes, and snippets.

@kenakingkong
Created June 1, 2023 07:06
Show Gist options
  • Save kenakingkong/c7ab4521e00e5bd9feb46453be12a35e to your computer and use it in GitHub Desktop.
Save kenakingkong/c7ab4521e00e5bd9feb46453be12a35e to your computer and use it in GitHub Desktop.
convert images to webp format
import os
from PIL import Image
from optparse import OptionParser
"""
Convert to webp
This script convert image(s) to webp format
- Accepts png, jpg, jpeg formats
- Given an image, converts image to webp
- Given a folder, converts images in that folder to webp
usage: python3 convert_to_webp.py <foldername|filename> [options]
options:
-l, --lossless Use lossless compression (default lossy)
-e, --exact Preserve transparent rgb values (default false)
-q, --quality=<int> 0-100 quality for lossy, 0-100 speed for lossless, (default 80)
read docs for more info
https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#webp
"""
def parse_args():
usage = "usage: %prog <foldername|filename> [options]"
parser = OptionParser(usage)
parser.add_option("-l", "--lossless",
action="store_true",
default=False,
dest="lossless",
help="Use lossless compression (default lossy)"
)
parser.add_option("-e", "--exact",
action="store_true",
default=False,
dest="exact",
help="Preserve transparent rgb values (default false)"
)
parser.add_option("-q", "--quality",
action="store",
type="int",
default=80,
dest="quality",
help="0-100 quality for lossy, 0-100 speed for lossless, (default 80)"
)
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
return (options, args)
def get_destination(source):
return os.path.splitext(source)[0] + ".webp"
def convert_to_webp(source, options):
image = Image.open(source)
destination = get_destination(source)
exif_data = image.getexif()
image.save(
fp = destination,
format = "webp",
exif = exif_data,
lossless = options.lossless,
exact = options.exact,
quality = options.quality
)
return destination
def main():
(options, args) = parse_args()
file_path = args[0]
if (os.path.isfile(file_path)):
new_path = convert_to_webp(file_path, options)
print(new_path)
else:
for file in os.listdir(file_path):
if (file.endswith(tuple([".png", ".jpg", ".jpeg"]))):
new_path = convert_to_webp(f"{file_path}/{file}", options)
print(new_path)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment