Skip to content

Instantly share code, notes, and snippets.

@anhtran
Created June 13, 2019 05:09
Show Gist options
  • Save anhtran/fc0611c0b69c5ecb2c8ea0bc51f33421 to your computer and use it in GitHub Desktop.
Save anhtran/fc0611c0b69c5ecb2c8ea0bc51f33421 to your computer and use it in GitHub Desktop.
Building, convert images to WebP in a single command
import glob
import os
import click
from webptools import webplib as webp
@click.group()
def cli():
pass
def replace_webp_ext(url: str):
for x in ['jpg', 'jpeg', 'gif', 'png']:
if url.lower().endswith('.' + x):
ext = url.split('.')[-1]
return url.replace('.' + ext, '.webp')
return
@cli.command(name='dir')
@click.argument('abs_path', nargs=1, type=str)
def make_in_dir(abs_path):
count = 0
if abs_path.endswith('/'):
abs_path = abs_path[:-1]
files_grabbed = []
for e in ('*.jpg', '*.png', '*.gif', '*.jpeg'):
for x in glob.glob(abs_path + '/**/' + e):
if not os.path.isfile(replace_webp_ext(x)):
files_grabbed.append(x)
for item in files_grabbed:
click.echo('=> ' + item)
count += 1
# build webp
webp_fn = replace_webp_ext(item)
if item.endswith('gif'):
webp.gifwebp(item, webp_fn, "-q 80")
else:
webp.cwebp(item, webp_fn, "-q 80")
click.secho('OK', fg='green')
click.secho('Processed %s items' % count, fg='green')
if __name__ == '__main__':
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment