|
import os |
|
import glob |
|
import shutil |
|
from PIL import Image |
|
|
|
def create_collage_image(folder, index, start_index=1, end_index=9): |
|
|
|
image_gap = 20 |
|
outer_gap = 30 |
|
bg_color = (8, 9, 11) |
|
|
|
|
|
index.reverse() |
|
|
|
|
|
images = [os.path.join(folder, f"{idx}.*") for idx in index] |
|
images = [glob.glob(image_path)[0] for image_path in images if glob.glob(image_path)] |
|
print(images) |
|
|
|
|
|
total_images = len(images) |
|
if start_index < 1: |
|
start_index = 1 |
|
if end_index > total_images: |
|
end_index = total_images |
|
if start_index > end_index: |
|
raise ValueError(f"Invalid start or end index. Total images available: {total_images}") |
|
|
|
|
|
images = images[start_index - 1:end_index] |
|
|
|
|
|
loaded_images = [Image.open(image).convert("RGBA") for image in images] |
|
|
|
|
|
min_width = min(img.width for img in loaded_images) |
|
min_height = min(img.height for img in loaded_images) |
|
|
|
|
|
required_images = len(loaded_images) |
|
rows = (required_images + 2) // 3 |
|
|
|
|
|
total_width = min_width * 3 + image_gap * 2 + outer_gap * 2 |
|
total_height = min_height * rows + image_gap * (rows - 1) + outer_gap * 2 |
|
|
|
|
|
collage_image = Image.new('RGB', (total_width, total_height), bg_color + (255,)) |
|
|
|
|
|
for idx, image in enumerate(loaded_images): |
|
row = idx // 3 |
|
col = idx % 3 |
|
resized_image = image.resize((min_width, min_height)) |
|
x = outer_gap + col * (min_width + image_gap) |
|
y = outer_gap + row * (min_height + image_gap) |
|
collage_image.paste(resized_image, (x, y), resized_image) |
|
|
|
|
|
output_folder = f"./{folder}_sum" |
|
if os.path.exists(output_folder): |
|
shutil.rmtree(output_folder) |
|
os.makedirs(output_folder) |
|
|
|
|
|
collage_image.save(os.path.join(output_folder, "sum.jpg"), quality=90) |
|
|