from PIL import Image
import os
import math
import sys

# 입력 및 출력 디렉토리 설정
input_directory = "/ltb/media/ltb/90887173887158A4/Users/ltb/쓰러짐gif용"
output_directory = "/ltb/media/ltb/90887173887158A4/Users/ltb/gif_결과"

# 출력 디렉토리 내 새 하위 디렉토리 생성
def create_unique_subdirectory(base_path, base_name):
    index = 1
    new_path = os.path.join(base_path, f"{base_name}_{index}")
    while os.path.exists(new_path):
        index += 1
        new_path = os.path.join(base_path, f"{base_name}_{index}")
    os.makedirs(new_path)
    return new_path

# 이미지 파일 목록 가져오기
image_files = [os.path.join(input_directory, file) for file in sorted(os.listdir(input_directory)) if file.endswith(('.png', '.jpg', '.jpeg'))]

if not image_files:
    raise ValueError("디렉토리에 이미지 파일이 없습니다.")

# 이미지 크기 조정 함수
def resize_image(img, max_size):
    """
    이미지 크기 조정 함수
    :param img: PIL 이미지 객체
    :param max_size: (너비, 높이) 형태의 최대 크기
    :return: 크기 조정된 PIL 이미지 객체
    """
    img.thumbnail(max_size, Image.LANCZOS)
    return img

    # 예시 1: 원본 비율 유지하며 최대 크기 800x800으로 조정
    # resize_image(img, (800, 800))

    # 예시 2: 고정 크기 800x600으로 조정 (비율 유지 안 함)
    # resized_img = img.resize((800, 600), Image.LANCZOS)

    # 예시 3: 고해상도 이미지를 400x400으로 축소
    # resize_image(img, (400, 400))

# 이미지 열기
images = [Image.open(image_file) for image_file in image_files]

# 이미지 크기 조정 (원본 비율 유지)
max_size = (1000, 1000)  # 원하는 최대 크기 설정
images = [resize_image(img.copy(), max_size) for img in images]

# GIF 생성에 사용할 이미지 수
max_frames_per_gif = 1000  # 한 GIF에 포함될 이미지 수

# 새 하위 디렉토리 생성
subdirectory = create_unique_subdirectory(output_directory, "batch")

# 총 GIF 개수 계산
total_gifs = math.ceil(len(images) / max_frames_per_gif)

# 이미지 목록을 청크로 나누어 저장
for index, start in enumerate(range(0, len(images), max_frames_per_gif)):
    end = min(start + max_frames_per_gif, len(images))
    gif_images = images[start:end]
    
    # GIF 파일 이름에 숫자 추가
    gif_filename = f"output_{index+1}.gif"
    gif_path = os.path.join(subdirectory, gif_filename)
    
    # GIF로 저장
    gif_images[0].save(
        gif_path,
        save_all=True,
        append_images=gif_images[1:],
        duration=25,  # 각 프레임의 지속 시간 (밀리초)
        loop=0        # 0이면 무한 반복
    )
    
    # duration 변수 조절 예시:
    # duration=100 : 각 프레임이 100ms 동안 표시됨
    # duration=50  : 각 프레임이 50ms 동안 표시되어 GIF이 더 빠르게 재생됨
    # duration=200 : 각 프레임이 200ms 동안 표시되어 GIF이 더 느리게 재생됨

    # loop 변수 조절 예시:
    # loop=0 : GIF이 무한 반복됨
    # loop=1 : GIF이 한 번 반복됨
    # loop=5 : GIF이 5번 반복됨

    # 진행 퍼센테이지 계산
    percentage = ((index + 1) / total_gifs) * 100
    # 간결한 진행 퍼센테이지 출력
    sys.stdout.write(f"\r진행 중: {percentage:.2f}%")
    sys.stdout.flush()
    
    print(f"GIF가 {gif_path}로 저장되었습니다.")

print("\n모든 GIF 파일이 성공적으로 저장되었습니다.")
