Last active
December 7, 2021 00:25
-
-
Save toddbirchard/4829231fa021cc3d5b4f54afba65014d to your computer and use it in GitHub Desktop.
Recursively retrieve all images in a given site, generate retina images, convert all images to webp format.
This file contains 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
import os | |
import json | |
import glob | |
import PIL | |
from PIL import Image | |
def get_all_images(): | |
"""Create an array of PNGs and JPGs.""" | |
img_arr = [] | |
for filename in glob.iglob('content/images/**/**.*g', recursive=True): | |
if '/size/' not in filename: | |
img_arr.append(filename) | |
return img_arr | |
def create_webp_images(image): | |
"""Creates a webp copy for each image.""" | |
file, ext = os.path.splitext(image) | |
im = Image.open(image).convert("RGB") | |
im.save(file + ".webp", "WEBP") | |
print(file, '.webp') | |
return im | |
def add_2x_to_image(image): | |
"""Adds @2x to filename.""" | |
if "@2x" not in image: | |
new_filename = str(image).replace('.jpg', '@2x.jpg') | |
new_filename = str(image).replace('.png', '@2x.png') | |
print(new_filename) | |
return new_filename | |
return None | |
def create_new_images(): | |
"""Create new optimized images. | |
1. Get all images in directory. | |
2. Generate retina filenames for images. | |
3. Create webp copies of both original and retina image. | |
""" | |
images = get_all_images() | |
retina_images = [add_2x_to_image(image) for image in images] | |
retina_images = list(filter(lambda a: a is not None, retina_images)) | |
all_images = images + retina_images | |
print('all images = ', len(all_images)) | |
new_images = [create_webp_images(image) for image in all_images] | |
return "Completed " + str(len(new_images)) + " images!" | |
create_new_images() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment