Image Resizing Script in Python

우선 패키지 설치하시고요

pip install Pillow
# 아니면 python -m pip install Pillow

아래 코드를 resize_image.py로 저장하세요

from PIL import Image
import os

file_extention = ".JPG"
input_dir = "./input"  # Replace with your actual input directory
output_dir = "./output"  # Replace with your desired output directory

def resize_image(input_dir, output_dir, new_width=800):
    """Resizes all JPG images in the input directory to the specified width and saves them in the output directory."""

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for filename in os.listdir(input_dir):
        if filename.endswith(file_extention):
            filepath = os.path.join(input_dir, filename)
            with Image.open(filepath) as img:
                width, height = img.size
                new_height = int(height * new_width / width)
                resized_img = img.resize((new_width, new_height), Image.LANCZOS)
                output_path = os.path.join(output_dir, filename)
                resized_img.save(output_path)
                print(f"Resized {filename} to {new_width}x{new_height}")

if __name__ == "__main__":
    resize_image(input_dir, output_dir)

input이라는 폴더 하나 만드시고, 거기다가 JPG이미지 넣으세요. 혹시 확장자가 jpg소문자이면 코드에서 file_extention값을 소문자로 바꿔주세요. 저는 함수 호출할때 새로 만들 이미지의 가로크기를 지정해주도록 했는데 기본값은 800이거든요. 혹시 다른 사이즈 넣고 싶으시면 함수 호출할때 같이 넣어주시면 되요. 이제 코드를 실행할게요.

python3 resize_image.py

그러면 결과를 출력하면서 이미지를 리사이징합니다.

Resized IMG_0809.JPG to 800x600
Resized IMG_0821.JPG to 800x600
...

실행이 끝나고 나면 output이라는 폴더가 생겼을거에요.

감사합니다.