Skip to content

Instantly share code, notes, and snippets.

@FFY00
Created January 24, 2023 23:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FFY00/995947e5a506d58ac67c5b16d47151ca to your computer and use it in GitHub Desktop.
Save FFY00/995947e5a506d58ac67c5b16d47151ca to your computer and use it in GitHub Desktop.
Resize WEBP animations
import argparse
import textwrap
from PIL import Image, ImageSequence
def main() -> None:
parser = argparse.ArgumentParser(
description=textwrap.indent(
textwrap.dedent(
"""
Simple tool to resize WEBP animations based on the Pillow library.
For the resize options, check:
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.resize
For the WEBP writing options, check:
https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#webp
"""
).strip(),
' ',
),
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument('input', type=str, help='input file')
parser.add_argument('output', type=str, help='output file')
resize_group = parser.add_argument_group('resize', 'Options related to the image resizing')
resize_group.add_argument('size', type=int, nargs='+')
resize_group.add_argument('--resample', type=str, choices=Image.Resampling.__members__.keys(), required=False)
resize_group.add_argument('--reducing-gap', type=int, required=False)
webp_group = parser.add_argument_group('webp', 'Options related to the WEBP writing')
webp_group.add_argument('--lossless', type=bool, required=False)
webp_group.add_argument('--quality', type=int, required=False)
webp_group.add_argument('--method', type=int, required=False)
webp_group.add_argument('--exact', type=bool, required=False)
args = parser.parse_args()
if len(args.size) == 1:
size = (args.size[0], args.size[0])
elif len(args.size) == 2:
size = tuple(args.size)
else:
raise ValueError(f'Invalid size argument: {args.size}')
resize_args = {'size': size}
if args.resample:
resize_args['resample'] = Image.Resampling.__members__[args.resample]
if args.reducing_gap:
resize_args['reducing_gap'] = args.reducing_gap
webp_args = {}
if args.lossless:
webp_args['lossless'] = args.lossless
if args.quality:
webp_args['quality'] = args.quality
if args.method:
webp_args['method'] = args.method
if args.exact:
webp_args['exact'] = args.exact
original = Image.open(args.input)
resized_frames = ImageSequence.all_frames(original, lambda im: im.resize(**resize_args))
resized_frames[0].save(
args.output,
save_all=True,
append_images=resized_frames[1:],
**webp_args,
)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment