Skip to content

Commit bcc5f10

Browse files
committed
combined all the srcset step into one file
1 parent def523e commit bcc5f10

File tree

1 file changed

+159
-0
lines changed

1 file changed

+159
-0
lines changed

scripts/create_srcsets.py

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
# script for creating srcset image copies for upload to CDN
2+
import os
3+
from PIL import Image
4+
import shutil
5+
6+
# Step 1
7+
# a function that will:
8+
# 1. Iterate through all files in the 'start' directory.
9+
# 2. For each file, check if it is a JPG or JPEG image (case-insensitive).
10+
# 3. Open the image to get its dimensions.
11+
# 4. Rename the file according to the rules (extension to .jpg, append .WIDTHxHEIGHT).
12+
# 5. Save the renamed file in the 'renamed' directory.
13+
14+
def rename_images_add_dimensions(start_dir, renamed_dir, test=False):
15+
if test:
16+
print('cwd =', os.getcwd())
17+
if not os.path.exists(start_dir):
18+
os.makedirs(start_dir)
19+
if not os.path.exists(renamed_dir):
20+
os.makedirs(renamed_dir)
21+
for filename in os.listdir(start_dir):
22+
file_lower = filename.lower()
23+
if file_lower.endswith('.jpg') or file_lower.endswith('.jpeg'):
24+
name, ext = os.path.splitext(filename)
25+
if test:
26+
print("name:", name, ", ext:", ext)
27+
ext = '.jpg' # always use .jpg, not .jpeg
28+
img_path = os.path.join(start_dir, filename)
29+
try:
30+
with Image.open(img_path) as img:
31+
width, height = img.size
32+
except Exception as e:
33+
print(f"Could not open {filename}: {e}")
34+
continue
35+
new_name = f"{name}.{width}x{height}{ext}"
36+
if test:
37+
print("new_name: ", new_name)
38+
print(f'{{ src: "{new_name}", alt: "A photo" }},')
39+
new_path = os.path.join(renamed_dir, new_name)
40+
shutil.copy2(img_path, new_path)
41+
42+
# append a Typescript snippet to a file for pasting into 'src/photos.tx'
43+
code = f'{{ src: "{new_name}", alt: "A photo" }},'
44+
with open('filenames-list.txt', 'a') as file:
45+
file.write(code + '\n')
46+
47+
# test step 1
48+
# if __name__ == "__main__":
49+
# test_dir1 = 'photos/test/test1' # original photo named XXXX.YYY.jpg
50+
# test_dir2 = 'photos/test/test2' # original photo with dimensions added to name
51+
# # i.e., XXXX.YYY.WIDTHxHEIGHT.jpg
52+
# rename_images_add_dimensions(test_dir1, test_dir2, test=True)
53+
54+
# step 2
55+
# This function will create a srcset of resized copies of each JPG image
56+
# in the 'start' directory, saving them in the destination
57+
# directory with the specified filename format.
58+
59+
def create_resized_copies(start_dir, dest_dir, test=False):
60+
widths = [1080, 640, 384, 256, 128, 96, 64, 48]
61+
if not os.path.exists(dest_dir):
62+
os.makedirs(dest_dir)
63+
for filename in os.listdir(start_dir):
64+
if filename.lower().endswith('.jpg'):
65+
filepath = os.path.join(start_dir, filename)
66+
with Image.open(filepath) as img:
67+
for w in widths:
68+
# Calculate new height to maintain aspect ratio
69+
aspect_ratio = img.height / img.width
70+
new_height = int(w * aspect_ratio)
71+
resized_img = img.resize((w, new_height), Image.LANCZOS)
72+
# Build new filename
73+
name, ext = os.path.splitext(filename)
74+
new_filename = f"{name}.{w}w{ext}"
75+
dest_path = os.path.join(dest_dir, new_filename)
76+
if test:
77+
print("dest_path:", dest_path)
78+
resized_img.save(dest_path, "JPEG")
79+
80+
81+
# if __name__ == "__main__":
82+
# test_dir2 = 'photos/test2'
83+
# test_dir3 = 'photos/test3'
84+
# create_resized_copies(test_dir2, test_dir3, test=True)
85+
86+
87+
# step 3
88+
# add width to the end of the original full-sized image name and copy the
89+
# renamed image to the 'dst_dir' directory.
90+
def copy_and_rename_jpg_images(src_dir, dst_dir, test=False):
91+
if not os.path.exists(dst_dir):
92+
os.makedirs(dst_dir)
93+
for filename in os.listdir(src_dir):
94+
if filename.lower().endswith('.jpg'):
95+
src_path = os.path.join(src_dir, filename)
96+
try:
97+
with Image.open(src_path) as img:
98+
width, _ = img.size
99+
except Exception as e:
100+
print(f"Error opening {filename}: {e}")
101+
continue
102+
name, ext = os.path.splitext(filename)
103+
new_filename = f"{name}.{width}w{ext}"
104+
dst_path = os.path.join(dst_dir, new_filename)
105+
shutil.copy2(src_path, dst_path)
106+
if test:
107+
print(f"Copied and renamed: {src_path} -> {dst_path}")
108+
109+
# if __name__ == "__main__":
110+
# src_dir = "photos/test2"
111+
# dst_dir = "photos/test3"
112+
# copy_and_rename_jpg_images(src_dir, dst_dir, test=True)
113+
114+
# step 4
115+
def cleanup_files(src_dir, dest_dir):
116+
# source_directory = "path/to/source_folder" # Replace with your source directory path
117+
# destination_directory = "path/to/destination_folder" # Replace with your destination directory path
118+
119+
# Create the destination directory if it doesn't exist
120+
os.makedirs(dest_dir, exist_ok=True)
121+
122+
# Get a list of all files in the source directory
123+
files_to_move = os.listdir(src_dir)
124+
125+
# Iterate through each file and move it
126+
for filename in files_to_move:
127+
source_path = os.path.join(src_dir, filename)
128+
destination_path = os.path.join(dest_dir, filename)
129+
130+
# Check if it's a file (and not a subdirectory) before moving
131+
if os.path.isfile(source_path):
132+
shutil.move(source_path, destination_path)
133+
print(f"Moved '{filename}' to '{dest_dir}'")
134+
else:
135+
print(f"Skipping '{filename}' as it is not a file.")
136+
137+
138+
# if __name__ == "__main__":
139+
# src_dir = "photos/input/" # Replace with the actual path to your file
140+
# dest_dir = "photos/archives/" # Replace with the actual path to your destination directory
141+
# cleanup_files(src_dir, dest_dir)
142+
143+
144+
start='photos/input/' # this dir must exist before running this code; put the to-be-processed photos here
145+
renamed='photos/work_in_process/' # temporary location for renamed version of original photo
146+
dest='photos/srcset/' # final output of photo srcset for upload to CDN; there should be nine versions of each photo here
147+
archives = 'photos/archives/'
148+
149+
if __name__ == "__main__":
150+
rename_images_add_dimensions(start, renamed)
151+
# step01_add_dimensions_to_original_image_names.rename_images_add_dimensions(start, renamed)
152+
# (step02_create_resized_image_copies_for_srcset.
153+
create_resized_copies(renamed, dest)
154+
# (step03_copy_orig_image_rename_for_srcset.
155+
copy_and_rename_jpg_images(renamed, dest)
156+
# (step04_cleanup.
157+
cleanup_files(start, archives)
158+
#step04_cleanup.
159+
cleanup_files(renamed, archives)

0 commit comments

Comments
 (0)