cosmo / sum.py
tripleS-Dev
start
1c1f3a2
import os
import glob
import shutil
from PIL import Image
def create_collage_image(folder, index, start_index=1, end_index=9):
# ํด๋” ๋‚ด ์ด๋ฏธ์ง€ ํŒŒ์ผ์„ index ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜์—ฌ ๊ฐ€์ ธ์˜ค๊ธฐ
image_gap = 20
outer_gap = 30
bg_color = (8, 9, 11)
# index ๋ฆฌ์ŠคํŠธ๋ฅผ ์—ญ์ˆœ์œผ๋กœ ์ฒ˜๋ฆฌ
index.reverse()
# index ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•˜์—ฌ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ƒ์„ฑ
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]
# ์ด๋ฏธ์ง€ ๋กœ๋“œ ๋ฐ RGBA ํฌ๋งท์œผ๋กœ ๋ณ€ํ™˜
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)
# 3์—ด์„ ์œ ์ง€ํ•˜๋ฉฐ ํ–‰ ์ˆ˜ ๊ณ„์‚ฐ
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
# ๋นˆ ์บ”๋ฒ„์Šค ์ƒ์„ฑ (RGB ํฌ๋งท์œผ๋กœ ๋ณ€ํ™˜)
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)