hackshaw commited on
Commit
068355c
·
verified ·
1 Parent(s): 12282f0

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +52 -0
utils.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw, ImageFont
2
+ import os
3
+
4
+ accepted_extensions = (".jpg", ".jpeg", ".png")
5
+
6
+ def create_contact_sheet(image_paths, output_dir, columns=4, rows=6, padding=5):
7
+ # Define the size of the contact sheet
8
+ image_size = 100 # Each image and padding is 100x100 pixels
9
+ contact_sheet_width = columns * image_size
10
+ contact_sheet_height = rows * image_size
11
+
12
+ # Create output directory if it doesn't exist
13
+ os.makedirs(output_dir, exist_ok=True)
14
+
15
+ # Initialize variables for the current contact sheet
16
+ current_sheet = 1
17
+ x = 0
18
+ y = 0
19
+ contact_sheet = Image.new('RGB', (contact_sheet_width, contact_sheet_height), color='white')
20
+ draw = ImageDraw.Draw(contact_sheet)
21
+
22
+ for filename in image_paths:
23
+ if filename.lower().endswith(accepted_extensions):
24
+ img = Image.open(filename)
25
+ # Resize the image to fit the grid cell
26
+ img.thumbnail((image_size - padding * 2, image_size - padding * 2), Image.Resampling.LANCZOS)
27
+ # Paste the image into the contact sheet with padding
28
+ contact_sheet.paste(img, (x + padding, y + padding))
29
+ # Draw the file name below the image
30
+ draw.text((x + padding, y + image_size - padding), os.path.basename(filename), fill='black')
31
+ # Move position to the right for the next image
32
+ x += image_size
33
+ if x >= contact_sheet_width:
34
+ x = 0
35
+ y += image_size
36
+ if y >= contact_sheet_height:
37
+ # Save the current contact sheet
38
+ output_file = os.path.join(output_dir, f'contact_sheet_{current_sheet}.jpg')
39
+ contact_sheet.save(output_file, "JPEG")
40
+ print(f"Saved contact sheet {current_sheet}")
41
+ # Start a new contact sheet
42
+ current_sheet += 1
43
+ y = 0
44
+ contact_sheet = Image.new('RGB', (contact_sheet_width, contact_sheet_height), color='white')
45
+ draw = ImageDraw.Draw(contact_sheet)
46
+
47
+ # Save the last contact sheet
48
+ output_file = os.path.join(output_dir, f'contact_sheet_{current_sheet}.jpg')
49
+ contact_sheet.save(output_file, "JPEG")
50
+ print(f"Saved contact sheet {current_sheet}")
51
+
52
+ return current_sheet # Return the number of contact sheets generated