이미지 파일을 변환해야 하는 경우가 잦다.
그래서 폴더 않에 있는 파일 형식을 한번에 바꾸도록 파이썬 코드를
Cursor에게 부탁해서 만들었다
기본적으로
|
을 목적으로 만들어 졌고
다음과 같은 파일 형식은 모두 다룰 수 있지만
- JPEG (.jpg, .jpeg)
- PNG (.png)
- GIF (.gif)
- BMP (.bmp)
- WebP (.webp)
- TIFF (.tiff, .tif)
- ICO (.ico) - 윈도우 아이콘
- PPM (.ppm) - Portable Pixmap
- PGM (.pgm) - Portable Graymap
- PBM (.pbm) - Portable Bitmap
- PCX (.pcx) - PC Paintbrush
- EPS (.eps) - Encapsulated PostScript
- IM (.im) - IFUNC Image Memory
- SGI (.sgi) - Silicon Graphics Image
일부 변환은 품질 손실이나 기능 제한이 있을 수 있고(예 GIF -> JPG 변환 시 애니메이션 정보가 손실), 모든 조합이 실용적이지는 않다(예: BMP는 용량이 커서 잘 사용하지 않음)
이제 실행해 보자
import os
from PIL import Image
def convert_image_format(folder_path, from_format, to_format):
"""
지정된 형식의 이미지를 다른 형식으로 변환합니다.
:param folder_path: 이미지가 있는 폴더 경로
:param from_format: 원본 이미지 형식 (예: 'webp', 'jpg', 'png')
:param to_format: 변환할 이미지 형식 (예: 'webp', 'jpg', 'png')
"""
# 형식에서 점 제거 및 소문자로 변환
from_format = from_format.lower().strip('.')
to_format = to_format.lower().strip('.')
if not os.path.exists(folder_path):
print(f"폴더를 찾을 수 없습니다: {folder_path}")
return
# 지원하는 형식 확인
supported_formats = {'webp', 'jpg', 'jpeg', 'png'}
if from_format not in supported_formats or to_format not in supported_formats:
print("지원하지 않는 형식입니다. webp, jpg, png 형식만 지원합니다.")
return
for filename in os.listdir(folder_path):
if filename.lower().endswith(f'.{from_format}'):
input_path = os.path.join(folder_path, filename)
output_filename = os.path.splitext(filename)[0] + f'.{to_format}'
output_path = os.path.join(folder_path, output_filename)
try:
with Image.open(input_path) as img:
# PNG로 변환할 때는 RGBA 모드 유지, 그 외에는 RGB로 변환
if to_format.lower() == 'png':
if img.mode != 'RGBA':
img = img.convert('RGBA')
else:
img = img.convert('RGB')
# 이미지 저장
if to_format.lower() == 'jpg':
img.save(output_path, 'JPEG', quality=95)
else:
img.save(output_path, to_format.upper())
print(f"변환 완료: {filename} -> {output_filename}")
# 원본 파일 삭제
os.remove(input_path)
print(f"원본 파일 삭제됨: {filename}")
except Exception as e:
print(f"파일 변환 중 오류 발생 {filename}: {e}")
# 사용 예시
if __name__ == "__main__":
folder_path = r"c:\Users\폴더" # 폴더 경로를 지정하세요
# WebP -> JPG 변환
convert_image_format(folder_path, 'webp', 'jpg')
# PNG -> JPG 변환
# convert_image_format(folder_path, 'png', 'jpg')
# WebP -> PNG 변환
# convert_image_format(folder_path, 'webp', 'png')
폴더 내에 있는
모든 webp 파일을 jpg 파일로 변환 시킨다
추가로 코드에서는 지정한 형식(`from_format`)의 파일만 검사하고 변환하기 때문에,
다른 형식의 파일들은 전혀 영향을 받지 않는다.
예) webp > jpg 에 경우
폴더/ ├── image1.webp ├── image2.webp ├── image3.jpg ├── image4.jpg └── image5.png |
폴더/ ├── image1.jpg (변환됨) ├── image2.jpg (변환됨) ├── image3.jpg (기존 파일) ├── image4.jpg (기존 파일) └── image5.png (기존 파일) |
Cursor는 GPT 처럼 챗을 통해 코드를 작성해준다.
다른 점이라면, GPT나 클로드를 통해 코드를 부탁해서 옮기는 것과 달리
더 긴 코드도 작성 가능하고, 수정사항을 쉽게 확인 가능하다.
또 코드에 대한 설명을 알아서 해준다는 점, 언제든지 아무 코드파일을 지목해서 수정을 부탁 할 수 있다는 점이 무척 편하다.
나같이 개발을 모르는 일반인도 간단한 것은 즉각 만들 수 있도록 해준다.
'AI 툴 활용법' 카테고리의 다른 글
GPT로 유료 사이트 해킹하기? (4) | 2024.12.02 |
---|---|
GPT, Claude, Perplexity: 어떤 AI를 선택할 것인가? (1) | 2024.11.30 |
GPT 자기소개 랜딩페이지 만들기 (생각보다 너무 쉽다) (2) | 2024.11.19 |
Ai로 애니메이션 만들기 test1s (0) | 2024.11.17 |
폴더 및 파일 정리 feat GPT (2) | 2024.11.09 |