Created
August 20, 2023 13:04
-
-
Save srcnalt/7a062f464b36a09f392c3b732893fc0f to your computer and use it in GitHub Desktop.
Convert GIF files to WEBP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# convert gifs to webp files with quality 70 and 1 frame skip. | |
# ~85% size reduction | |
import os | |
from PIL import Image, ImageSequence | |
def get_files(directory='.', extensions=None): | |
found = [] | |
for root, dirs, files in os.walk(directory): | |
for file in files: | |
if file.endswith(extensions): | |
found.append(os.path.join(root, file)) | |
total_size = sum(os.path.getsize(gif) for gif in found) | |
file_count = len(found) | |
print(f"Total {extensions} files: {file_count}") | |
print(f"Total size: {total_size / (1024*1024):.2f} MB") | |
return found | |
def gif_to_webp(files, quality=70): | |
for file in files: | |
input_gif_path = file | |
output_webp_path = file.replace('.gif', '.webp') | |
with Image.open(input_gif_path) as gif: | |
frames = [frame.convert('RGB') for index, frame in enumerate(ImageSequence.Iterator(gif)) if index % 2 == 0] | |
duration = gif.info.get('duration', 100) * 2 | |
frames[0].save( | |
output_webp_path, | |
format='WEBP', | |
save_all=True, | |
append_images=frames[1:], | |
loop=gif.info.get('loop', 0), | |
quality=quality, | |
duration=duration | |
) | |
print(f"Converted {input_gif_path} to {output_webp_path}.") | |
def delete_files(files): | |
for file in files: | |
os.remove(file) | |
print(f"Deleted {file}.") | |
if __name__ == "__main__": | |
files = get_files("./", '.gif') | |
gif_to_webp(files) | |
get_files("./", '.webp') | |
delete_files(files) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment