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)