1200x628, 1200x1500, 1200x1200
적당한 이미지를 제작 후 권장 사이즈에 맞춰서 다양한 사이즈의 이미지를 생성합니다.
- images 폴더 생성
- images에 초안 이미지 넣기
- 스크립트 실행
- 결과물을 resized_images폴더에서 확인한다.
| import os | |
| from PIL import Image | |
| def crop_image(img, crop_width, crop_height, position='center'): | |
| img_width, img_height = img.size | |
| if position == 'center': | |
| return img.crop(( | |
| (img_width - crop_width) // 2, | |
| (img_height - crop_height) // 2, | |
| (img_width + crop_width) // 2, | |
| (img_height + crop_height) // 2 | |
| )) | |
| elif position == 'top': | |
| return img.crop(( | |
| (img_width - crop_width) // 2, | |
| 0, | |
| (img_width + crop_width) // 2, | |
| crop_height | |
| )) | |
| elif position == 'bottom': | |
| return img.crop(( | |
| (img_width - crop_width) // 2, | |
| img_height - crop_height, | |
| (img_width + crop_width) // 2, | |
| img_height | |
| )) | |
| else: | |
| raise ValueError("Invalid position value. Use 'center', 'top', or 'bottom'.") | |
| def resize_image(image_path, output_sizes, output_folder, crop_position='center'): | |
| with Image.open(image_path) as img: | |
| img_name = os.path.splitext(os.path.basename(image_path))[0] | |
| for size in output_sizes: | |
| target_width, target_height = size | |
| # Calculate the cropping box | |
| img_width, img_height = img.size | |
| if img_width / img_height > target_width / target_height: | |
| new_height = img_height | |
| new_width = int(img_height * (target_width / target_height)) | |
| else: | |
| new_width = img_width | |
| new_height = int(img_width * (target_height / target_width)) | |
| # Crop the image based on the specified position | |
| img_cropped = crop_image(img, new_width, new_height, position=crop_position) | |
| # Resize the cropped image to the target size | |
| img_resized = img_cropped.resize((target_width, target_height), Image.LANCZOS) | |
| # Save the resized image | |
| output_path = os.path.join(output_folder, f"{img_name}_{target_width}x{target_height}_{crop_position}.png") | |
| img_resized.save(output_path) | |
| def generate(): | |
| # 원본 이미지가 들어 있는 폴더 경로 | |
| input_folder = "images" | |
| # 리사이즈된 이미지를 저장할 폴더 경로 | |
| output_folder = "resized_images" | |
| # 리사이즈할 크기 목록 | |
| sizes = [(1200, 1500), (1200, 1200), (1200, 628)] | |
| # 자를 위치 ('center', 'top', 'bottom') | |
| crop_positions = ['center', 'top', 'bottom'] | |
| # 출력 폴더가 존재하지 않으면 생성 | |
| os.makedirs(output_folder, exist_ok=True) | |
| # input_folder에 있는 모든 이미지 파일 처리 | |
| for filename in os.listdir(input_folder): | |
| if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): | |
| image_path = os.path.join(input_folder, filename) | |
| for position in crop_positions: | |
| resize_image(image_path, sizes, output_folder, crop_position=position) | |
| if __name__ == '__main__': | |
| generate() | |
| print("모든 이미지 리사이즈 및 크롭 완료!") |